react redux-toolkit 기본 예제

참고 : https://www.youtube.com/watch?v=9wrHxqI6zuM

생활코딩 유튜브 예제를 기반한 포스트입니다.

아래 예제는 다음 동작을 수행합니다.

  • 버튼을 클릭하면 counter 값이 올라감
  • counter 값을 노출시켜줌

예제 파일은 다음 세가지 파일로 구성 됩니다.

  • App.js – 메인 컴포넌트 파일
  • store.js – store 정의 파일
  • counterSlice.js – slice 정의 파일

App.js 파일

import React from 'react';
import './App.css';
import { Provider, useSelector, useDispatch } from 'react-redux';
import store from './store'
import { up } from './counterSlice';

function Counter() {
  const dispatch = useDispatch();
  const counter = useSelector(state => {
    return state.counter.value
  });
  return <div>
    <button onClick={() => { 
      // dispatch({ type: 'counter/up', step: 2 })
      dispatch(up(2))
    }}>+</button> { counter }
  </div>
}

export default function App() {
  return (
    <div id="container">
      <Provider store={ store }>
        <Counter></Counter>
      </Provider>
    </div>
  );
}

store.js

import { configureStore } from '@reduxjs/toolkit';
import counterSlice from './counterSlice';
  
  const store = configureStore({
    reducer: {
      counter: counterSlice.reducer
    }
  });

export default store;

counterSlice.js

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

const counterSlice = createSlice({
    name: 'counter',
    initialState: { value: 0 },
    reducers: {
      up: (state, action) => { 
        // state.value = state.value + action.step;
        state.value = state.value + action.payload;
      }
    }
});

export default counterSlice;
export const { up } = counterSlice.actions;

Leave a Reply