Redux를 사용하는 이유

2020. 7. 2. 13:50웹/React

Redux를 사용하는 이유

  • 중앙집중적인 데이터 Store를 통해 애플리케이션을 쉽게 개발

  • 관심사의 분리를 통한 코드의 복잡성 감소

  • Redux Dev Tools(상태에 대한 버전 관리)

 

 

 

예제) 컴포넌트 클릭 시, 컴포넌트들의 색을 전체 변경하는 코드

 

1) 리덕스가 존재하지 않는 코드

  • 컴포넌트가 기하급수적으로 늘어난다면, 관리해야하는 포인트가 너무 많음(강한 종속 관계)

    • 100개의 컴포넌트, 10000개의 코드 수정 필요(색 변경)

<body>
    <style>
        .component {
            border: 3px solid black;
            padding: 10px;
            margin-bottom: 10px;
        }
    </style>

    <div id="red"></div>
    <div id="green"></div>

    <script>
        function red() {
            document.querySelector('#red').innerHTML = `
                    <div class="component" id="component_red">
                        <h1>RED</h1>
                        <input type="button" value="클릭" onclick="
                            document.querySelector('#component_red').style.backgroundColor = 'red';
                            document.querySelector('#component_green').style.backgroundColor = 'red';
                        " />
                    </div>
                `;
        }
        red();

        function green() {
            document.querySelector('#green').innerHTML = `
                    <div class="component" id="component_green">
                        <h1>GREEN</h1>
                        <input type="button" value="클릭" onclick="
                            document.querySelector('#component_red').style.backgroundColor = 'green';
                            document.querySelector('#component_green').style.backgroundColor = 'green';
                        " />
                    </div>
                `;
        }
        green();
    </script>
</body>

 

 

 

2) 리덕스 사용

  • Redux Store에서 State 관리(중앙집중적으로 데이터 관리)

  • Action을 Store에 Dispatch를 통해 상태 변경 요청

  • Reducer에서 관련 컴포넌트 상태 변경

  • 상태 변경에 따른 각각의 컴포넌트 리렌더링(Subscribe)

 

=> 관심사의 분리를 통해 코드의 복잡성 감소

   서로 간의 의존성을 낮추고(De-Coupling), 각각의 컴포넌트는 StandAlone 

 

<html>
<head>
    <!-- Redux CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.js"></script>
</head>

<body>
    <style>
        .component {
            border: 3px solid black;
            padding: 10px;
            margin-bottom: 10px;
        }
    </style>

    <div id="red"></div>
    <div id="blue"></div>

    <script>
        // Dispatch 에 의한 Action 에 대해 새로운 State 반환
        function reducer(state, action) {
            let newState = {
                color: 'yellow'
            };
            switch (action.type) {
                case 'CHANGE_COLOR':
                    newState = Object.assign({}, state, {
                        color: action.color
                    });


                default:
                    return newState;
            }
            return newState;
        }
        const store = Redux.createStore(reducer);

        function red() {
            const state = store.getState();

            document.querySelector('#red').innerHTML = `
                    <div class="component" id="component_red" style="background-color: ${state.color}">
                        <h1>RED</h1>
                        <input type="button" value="클릭" onclick="
                            // 각각의 컴포넌트는 자기 자신에만 신경을 씀
                            // 상태 변경 요청
                            store.dispatch({type: 'CHANGE_COLOR', color: 'red'});
                        " />
                    </div>
                `;
        }
        // State 변경할 때마다 red 함수 호출
        store.subscribe(red);
        red();

        function blue() {
            const state = store.getState();

            document.querySelector('#blue').innerHTML = `
                    <div class="component" id="component_blue" style="background-color: ${state.color}">
                        <h1>BLUE</h1>
                        <input type="button" value="클릭" onclick="
                               // 각각의 컴포넌트는 자기 자신에만 신경을 씀
                            // 상태 변경 요청
                            store.dispatch({type: 'CHANGE_COLOR', color: 'blue'});
                        " />
                    </div>
                `;
        }
        // State 변경할 때마다 red 함수 호출
        store.subscribe(blue);
        blue();
    </script>
</body>
</html>

 

 

 

 

 

 

참고 

생활코딩 - Redux

 

' > React' 카테고리의 다른 글

Redux 정의  (0) 2020.07.01
SPA(Single Page Application)  (0) 2020.06.30
React 개념과 특징  (0) 2020.06.26