관리 메뉴

CASSIE'S BLOG

[슈퍼코딩] 70강 Redux 본문

PROGRAMMING/슈퍼코딩 강의 정리

[슈퍼코딩] 70강 Redux

ITSCASSIE1107 2023. 11. 14. 08:37

리덕스:
전세계에서 가장 많이 사용하는  전역 상태 (state) 관리 라이브러리

 

https://ko.redux.js.org/introduction/getting-started/

context Api랑 비슷한 역할을 한다.

자바스크립트 앱을 위한 예측 가능한 상태 컨테이너

 

redux-devtool

 


예측 가능하고,
중앙화 되어있으며
디버깅이 쉽고
유연함을 추구한다.

몇만줄 넘어서면 많은 상태를 자바스크립트 코드로 관리할 필요성이 생김

멘토스랑 콜라가 변화랑 비동기이다. 각각은 너무 좋은데 꼬이면 피곤해지는데 리덕스는 이거를 관리해줌

context API의 한계
규모가 커질수록 셋업과 관리가 복잡해진다는 단점이 있다.
잦은 상태 변화 시 퍼포먼스 이슈가 있다.

리액트팀에서 발표한 건데 상태관리를 전역네서 하면 동시다발적으로 상태관리를 할 수 있기때문에 퍼포먼스 이슈가 있다.

 

 

✅정리

액션 촉발 state 값 변경 

숫자가 증가했다 이런 액션을 받았을 때 그러면 나는 숫자값을 올려줄게
store로 데이터를 변경하는 로직을 실행하게되고 중앙데이터스토어가 값이 바뀌게되고
그 컴포넌트가 바뀐값을 구독하고 있다면 업데이트 된 "상태"로 받아볼 수가 있게되는거다. 

 


모든 데이터는 중앙데이터 저장소에서 꺼내온다.

컴포넌트는 중앙데이터저장소의 데이터를 구독 (subscription)을 통해서 데이터를 가져온다.

근데 뭐 중앙데이터저장소에서 데이터를
바꾸거나 할 일이 있잖아 바꾸는 역할을 하는거는 리듀서함수이다. (Reducer) 리듀서함수가 store(=중앙데이터저장소)의
데이터를 변경해준다.

액션을 전달해준다. Dispatch

이 액션은 다시 리듀서 함수로 간다.

데이터를 컴포넌트를 디스패치를 통해 액션으로 액션에서 리듀서로 전환
변경이 스토어를 통해서 일어나고 스토어에서 구독을 통해서 바뀐 state 값들이 계속해서 전달된다.

 

단방향 바인딩

한 방향으로 일어나는 사이클을 단방향 바인딩한다.

 

✅실습 따로 checkout 필요없음

그냥 아무 디렉토리가서
demoFolder가서
reduxDemo.js 파일을 만들어

 

 

 

 

✅ Redux 코어컨셉 

생소할 수 있지만 require 방식으로 import해줌

const redux = require('redux');

const counterReducer = (state, action) => {
    return state;
}

 

리듀서 함수 위에 사진처럼 state, action을 넣어주고 새로운 state가 return 되는거다. 

 

state = {counter: 0}, 
이게 무슨 말이냐면 
state가 값으로 받아지면 그 값을 return을 해주는데
만약에 값이 없으면 처음 counter값은 0으로 한다 이런 식으로 즉 초기값을 세팅할 수 있다.

 

✅state 초기값 설정

const redux = require('redux');

const counterReducer = (state = {counter: 0}, action) => {
    return state;
}

 

 

 

✅store 만들기

이 store는 redux에서 나온 store고 counterReducer로 변화를 줍니다. 이런 뜻이다. 

 

const redux = require('redux');

const counterReducer = (state = {counter: 0}, action) => {
    return state;
}

const store = redux.createStore(counterReducer);

 

 

 

 

 

component에서 subscribe한다했었죠? 구현해줘야함 이렇게
가장 최근의 latestState를 store의 getState() 메소드로 받아준다.

 

✅subscribe 만들기

const redux = require('redux');

const counterReducer = (state = {counter: 0}, action) => {
    return state;
}

const store = redux.createStore(counterReducer);

const counterSubscriber = () => {
    const latestState = store.getState();
console.log(latestState);
}

store.subscribe(counterSubscriber);

 

 

이 store에서 subscribe를 할 때 counterSubscriber을 통해서 subscribe를 하는데
그때마다 store의 가장 "최신 값"을 받아서 console로 찍어주겠다.

 

 


dispatch를 통해 action을 reducer로 한번 줘보는 리덕스의 기본 원리를 코드로 적용해보자.

 


dispatch를 통해 state와 action를 보내줘야하는데 state = {counter : 0} 이 부분에 이미 보내주고 있으니까 action만 보내주면 될 것 같다.

 

const redux = require('redux');

const counterReducer = (state = {counter: 0}, action) => {
    return state;
}

const store = redux.createStore(counterReducer);

const counterSubscriber = () => {
    const latestState = store.getState();
console.log(latestState);
}

store.subscribe(counterSubscriber);

store.dispatch({type: 'increment'});

 

 

이게 액션의 타입이 increment라는 뜻이다. 
그러면 reducer에서 type increment에 대해서 작업을 해줘야한다.

 

const redux = require('redux');

const counterReducer = (state = {counter: 0}, action) => {
    if (action.type === 'increment'){
        return {
            counter: state.counter + 1,
        }
    }
    return state;
}

const store = redux.createStore(counterReducer);

const counterSubscriber = () => {
    const latestState = store.getState();
console.log(latestState);
}

store.subscribe(counterSubscriber);

store.dispatch({type: 'increment'});

 

 

 

 

두번 찍으면 counter 가 2가 됨. 

 


 

npm install redux

const redux  = require(“redux”);
const counterReducer = (state = {counter : 0} , action) => { return state;
}


const store = redux.createStore(counterReducer);

const countrrSubscriber = () => {
    const latestState = store.getState();
console.log(latestState);
}

store.subscribe(counterSubscriber);

store.getState();이게 store에 최신값 받는거다.

이제 dispatch를 통해 action을 reducer로 한번 줘보는 리덕스의 기본 원리를 코드로 적용해보자.

dispatch를 통해 state와 action를 보내줘야하는데 state = {counter : 0} 이 부분에 이미 보내주고 있으니까 action만 보내주면 될 것 같다.

store.dispatch({type :’increment’});

컴포넌트에서 구독할 때 그 변경사항이 dispatch -> action -> Reducer -> Store 이렇게 한 방향으로 가게 하는 것이다.

반응형