본문 바로가기
Programming

React Redux Toolkit

by 나무수피아는 지식의 가지를 뻗어가는 공간입니다. 2025. 11. 3.
반응형

🌟 Redux Toolkit 완전 정복

Redux Toolkit은 Redux의 복잡함을 줄이고 생산성을 높여주는 공식 권장 도구입니다.
간단한 설정으로 상태관리, 비동기 처리, DevTools 연동까지 한 번에 가능합니다.

1. 설치

npm install @reduxjs/toolkit react-redux

2. 기본 구조

  • store.js: 전역 상태 관리소 생성
  • counterSlice.js: slice 정의
  • App.js: Provider로 전역 상태 연결
  • Counter.js: 상태 읽기/수정

3. counterSlice.js

import { createSlice } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: (state) => { state.value += 1 }, decrement: (state) => { state.value -= 1 }, incrementByAmount: (state, action) => { state.value += action.payload; } } }); export const { increment, decrement, incrementByAmount } = counterSlice.actions; export default counterSlice.reducer;

4. store.js

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

5. App.js

import React from 'react'; import { Provider } from 'react-redux'; import { store } from './store'; import Counter from './Counter'; function App() { return ( <Provider store={store}> <Counter /> </Provider> ); } export default App;

6. Counter.js

import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement, incrementByAmount } from './counterSlice'; function Counter() { const count = useSelector((state) => state.counter.value); const dispatch = useDispatch(); return ( <div> <h2>카운터: {count}</h2> <button onClick={() => dispatch(increment())}>+1</button> <button onClick={() => dispatch(decrement())}>-1</button> <button onClick={() => dispatch(incrementByAmount(5))}>+5</button> </div> ); } export default Counter;

7. 정리

  • Redux Toolkit의 createSlice()로 코드 간결화
  • configureStore()로 미들웨어 및 DevTools 자동 설정
  • Provider로 전역 상태 연결

📌 실전에서는 RTK Query, createAsyncThunk 등 비동기 처리도 함께 사용됩니다.

반응형