1. React Redux의 특징

  1. 중앙상태관리를 통해 다른 상태를 참조하여 상태값을 업데이트하는 로직을 생성할 수 있다.
  2. 상태값을 업데이트할 때, 이전의 상태값을 기반으로 업데이트할 수 있다.
  3. Redux 의 Dispatch() 또한 마찬가지로 rerender 에는 영향을 주지 않는다.

2. Redux Store와 StoreSlice

  • StoreSlice: store에 담기게 될 거대한 state를 프로그래머가 필요한 범위로 슬라이스 하여 꾸릴 수 있는 기능을 제공한다.

  • Store : Store Slice를 한곳으로 모아 종합 관리하는 거대한 공간이다.

3. useSelector()와 useDispatch()

  • useSelector() 는 콜백형태로 ‘StoreSlice의 이름’과 ‘StoreSlice의 key’를 통해 값을 불러올 수 있다.

[예]

import { useSelector } from 'react-redux';
import headerSlice from '경로'

const backColor = useSelector( state => {
	return state.headerSlice.backColor;
});
  • useDispatch() 는 콜백으로 사용할 수 없기 때문에, dispatch 변수에 담아 사용한다.
  • useDispatch() 는 store의 reducer를 들여다볼 수 있고, ‘StoreSlice의 이름’.actions.’StoreSlice의 reducer(수정할 값)’ 를 통해 state를 수정할 수 있다.

[예]

import { useDispatch } from 'react-redux';
import headerSlice from '경로'

const Header = () => {
    const dispatch = useDispatch();
	
    dispatch(headerSlice.actions.setBackColor('#FFF'));
}

4. store.js 와 StoreSlice.js

store는 storeSlice의 모음이다.

개발 순서는 먼저 기능에 맞게 구성할 storeSlice를 정의하고, 각각 흩어져있는 StoreSlice를 결합해야 한다.

[예 - store.js]

// configureStore <- storeSlice를 모으기 위한 거대한 스토어
import { configureStore } from '@reduxjs/toolkit';
import counterSlice from './counterSlice';
import highLightBackColorSlice from './highLightBackColorSlice';
import headerSlice from './headerSlice';

// storeSlice들을 하나로 합칠 Store를 만들자
const store = configureStore({
  // 여러 storeSlice 들을 하나의 거대한 reducer로 만들어줌
  reducer: {
    counter: counterSlice.reducer,
    highLightBackColor: highLightBackColorSlice.reducer,
    headerSlice: headerSlice.reducer,
  }
});

export default store;

[예 - counterSlice.js]

// createSlice <- storeslice 를 만들기 위함
import { createSlice } from '@reduxjs/toolkit';

const highLightBackColorSlice = createSlice({
    name: 'highLightBackColor',
    initialState: {value: 'white'},
    reducers: {
      setColor: (state, action) => {
        state.value = action.payload;
      }
    }
  });

  export default highLightBackColorSlice;

댓글남기기