«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
Recent Posts
Recent Comments
관리 메뉴

뉴히의 개발 로그

[TIL]20230620 - Redux( Reducer, combineReducers, useSelector) 본문

개발일지/TIL

[TIL]20230620 - Redux( Reducer, combineReducers, useSelector)

뉴히 2023. 6. 20. 22:52
Reducer : 변화를 일으키는 함수

리액트는 state의 변화가 있어야 리렌더링이 된다.

그래서 useState 사용시에 우리는 setState로 상태 변화를 주고 리렌더링이 발생하도록 했다.

redux 에서는 reducer가 그 역할을 한다.

state를 action의 type에 따라 변경한다.

 

리듀서는 인자로 state와 action 인자를 받는다. state에는 초기 상태값을 할당해 줘야한다.

<모듈 생성파일>

//초기상태값(state)
const initialState = {
    number: 0 // number라는 state : 초기값 0
};

//리듀서
const counter = (state = initialState, action) => {
    switch (action.type) {
        case PLUS_ONE:
            return {
                number: state.number + 1
            };     
        default:
            return state;
    }
};

그리고 이렇게 만든 모듈들은 store(중앙데이터관리소)에 연결해야한다. 연결해야 store에서 꺼내 사용할 수 있다.

<중앙 데이터 관리 파일>

import counter from '../modules/counter';
import users from '../modules/users';


// 리듀서를 모아 한개로 만들어둔 묶음 (기본 리듀서)
const rootReducer = combineReducers({    
    counter,//counter: counter   키 : 밸류 페어 (같은경우 생략)
    users: users
});

만들어둔 모듈 파일들을 import 하고 combineReducers API를 이용해서 리듀서를 모아 묶음으로 만들어 준다.

<App.jsx 파일>

const counter = useSelector((state) => {
    // 중앙저장소 전체 state
    return state.counter;
});

useSelector Hook을 이용해서 App.jsx 컴포넌트에서 중앙 데이터 관리소(store)를 조회할 수 있다.

 

어제는 React Hooks랑 오늘은 Redux.....

머리가 뱅뱅뱅 🤯 

조급한 마음에 집중도 더 안되고 계속 돌려보게된다...ㅠㅠ

정리도 안되고...

전부 다시 봐야겠다