[TIL] redux toolkit

oaksusu·2024년 2월 26일
0

TIL

목록 보기
2/36
post-thumbnail

0. 주제 선정하게 된 배경 :

스터디에서 진행하는 영화 예매 사이트 작업을 하면서
redux toolkit을 처음 사용하게 되었는데,
사용법이 익숙하지가 않아서 실수하는 부분들이 많았다.
혼자서 사용법에 대해서 훑어보고 실수했던 부분들을 상기시키기 위해 TIL 주제로 선정함

1. 제대로 알고 넘어가기

1-1. 사용법

1. 셋팅하기 : 한 곳에서 관리할 store와 slice들 만들기

  • store 생성 : store/index.js
import {configureStore} from '@reduxjs/toolkit';
import ExampleOneReducer from './slice/exampleOne';
import ExampleTwoReducer from './slice/exampleTwo';


export default configureStore({
	reducer: {
    	exampleOne: ExampleOneReducer,
        exampleTwo: ExampleTwoReducer
    }
})
  • slice 생성 : store/slice/exampleOne.js (exampleTwo도 동일한 방식)
import {createSlice} from '@reduxjs/toolkit';

const initialState = {
	somethingA: a,// ============== 실수했던 부분 1) useSelector로 원하는 state에 접근하기 위해서 이 이름을 사용함 ============== 
    somethingB: b
}

const reducers = {
	setA (state, {payload}) { // -------------------------- Redux slice의 액션 생성자
    	const {type,data} = payload; 
        state[type]= data;
    },
    setB (state, {payload}) { // -------------------------- Redux slice의 액션 생성자
    	const {type,data} = payload;
        state[type] = data
    }
}

const exampleSlice = createSlice({
	name: 'example1', 
    initialState,
    reducers
})

export const {setA, setB} = exampleSlice.actions;// ============== 실수했던 부분 2) dispatch를 사용하게 될때 어떤 액션자를 사용할지 지정 ============== 
export default exampleSlice.reducer;

2. 사용하기

  • 상태를 업데이트하고 싶은 경우
import {useDispatch} from 'react-redux';
import {setA} from '../../../../store/slice/exampleOne'

const dispatch = useDispatch();

dispatch(setA({type: 'somethingA', data: ABC})) // ============== 실수했던 부분 2) dispatch를 사용하게 될때 어떤 액션자를 사용할지 지정해줘야 함! ============== 
  • 상태를 불러오고 싶은 경우
import {useSelector} from 'react-redux';

const {somethingA} = useSelector(state => state.exampleOne); // ============== 실수했던 부분 1) useSelector로 원하는 state에 접근하기 위해서 이 이름을 사용해야함! ============== 

2. 적용해보기

커밋내역 : df3dfecc5dd4c3cf9777a683f3a7155f50f1ea47

profile
삐약

0개의 댓글