본문 바로가기
Study/Udemy-React-완벽 가이드

18.2 리덕스에 뛰어들기: 리덕스 툴킷, (feat. 유데미 React 완벽 가이드)

by NFAP0221S 2022. 6. 13.

https://www.udemy.com/course/best-react/

 

【한글자막】 React 완벽 가이드 with Redux, Next.js, TypeScript

Javascript부터 웹 어플리케이션 배포까지, React와 프론트엔드 최신 기술을 가장 쉽고 확실하게 배우는 법

www.udemy.com

이 게시물은 유데미 React 완벽 가이드 강의를 보고 메모를 남기는 게시물 입니다.


Redux Tookit

리덕스 툴킷 패키지를 설치하기 전에 기존의 리덕스 패키지는 삭제후 설치하면된다.

리덕스 툴킷에 포함되어 있기 때문에 리덕스 패키지만 삭제 후 리덕스 툴킷을 설치하면 된다.

npm install @reduxjs/toolkit

 

store

기존에 저장소를 redux에서 createStore로 생성하였다면

리덕스 툴킷 에서는 configureStore 로 생성하여준다.

reducer

리듀서 함수는 리덕스 툴킷에서 creatSlice 메서드를 사용한다.

creatSlice를 사용하면 if문이나 스위치문을 사용하지 않고 간결하게 코드를 작성할 수있다.

그리고 말 그대로 slice하여 코드를 작성할 수있는데 이것은 다음 글에서 작성한다.

코드

store 폴더 안의 index.js의 코드이다.

import { createSlice, configureStore } from '@reduxjs/toolkit';

// 초기화 상태 상수에 할당
const initialCounterState = { counter: 0, showCounter: true }; 

const counterSlice = createSlice({
  name: 'counter',
  initialState: initialCounterState, // state설정
  reducers: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
    increase(state, action) {
      state.counter = state.counter + action.payload;
    },
    toggleCounter(state) {
      state.showCounter = !state.showCounter;
    },
  },
});

// 초기화 상태 상수에 할당
const initialAuthState = { 
  isAuthenticated: false,
};

const authSlice = createSlice({
  name: 'authentication',
  initialState: initialAuthState, // state설정
  reducers: {
    login(state) {
      state.isAuthenticated = true;
    },
    logout(state) {
      state.isAuthenticated = false;
    },
  },
});

const store = configureStore({
  reducer: { counter: counterSlice.reducer, auth: authSlice.reducer },
});

export const counterActions = counterSlice.actions;
export const authActions = authSlice.actions;

export default store;

여기서  counterSlice 와 authSlice 는 .actions 와 맵핑하여 export 되고 있는 것을 생각해두자

useSelctor, useDispatch

다음은 컴포넌트 폴더의 Counter.js 에서 useSelctor와 useDispatch 를 알아보자.

import

임포트는 리액트 리덕스에서 할 수 있다.

import { useSelector, useDispatch } from 'react-redux';

useDispatch

디스패치 메서드를 상수에 할당한다.

  const dispatch = useDispatch();

아래의 코드처럼 함수가 실행되면 디스패치 해주는데 , index.js 에서 export 된 conterActions를 참고하면

아래의 함수가 실행될 때 어떻게 실행될지를 알 수 있다.

  const incrementHandler = () => {
    dispatch(counterActions.increment());
  };
  const increaseHandler = () => {
    dispatch(counterActions.increase(10)); // { type: SOME_UNIQUE_IDENTIFIER, payload: 10 }
  };
  const decrementHandler = () => {
    dispatch(counterActions.decrement());
  };
  const toggleCounterHandler = () => {
    dispatch(counterActions.toggleCounter());
  };

useSelector

useSelector 는 저장소에 바로 접근하여 원하는 state를 선택해준다.

즉 index.js 에서 원하는 state를 선택하는 것이다.

  const counter = useSelector((state) => state.counter.counter);
  const show = useSelector((state) => state.counter.showCounter);

그리고 선택된 state를 리턴에 출력하면 동적인 변화를 줄 수 있다.

  return (
    <main className={classes.counter}>
      <h1>Redux Counter</h1>
      {show && <div className={classes.value}>{counter}</div>}
      <div>
        <button onClick={incrementHandler}>Increment</button>
        <button onClick={increaseHandler}>Increase by 10</button>
        <button onClick={decrementHandler}>Decrement</button>
      </div>
      <button onClick={toggleCounterHandler}>Toggle Counter</button>
    </main>
  );
};