Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

죽이죽이

React : Redux ToolKit (RTK) 본문

React

React : Redux ToolKit (RTK)

죽이죽이 2024. 2. 27. 15:00

Redux ToolKit

※ Redux ToolKit 설치
- redux toolkit :
수동으로 작성하는 Redux 로직에서 "보일러 플레이트"를 제거하고, 흔한 실수를 방지하고, 기본적인 Redux 작업을 간단하게 만드는 API를 제공한다.
npm i @reduxjs/toolkit


※ 기본 사용법
import { configureStore, createSlice } from "@reduxjs/toolkit";

// 초기 상태값 정의
const initialState = { counter: 0, showCounter: true };

const counterSlice = createSlice({
  // 슬라이스명
  name: "counter",
  // 초기 상태값
  initialState,
  // 리듀서 함수들 정의
  reducers: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
    increase(state, action) {
      // payload에 증가값이 넘어옴
      state.counter += action.payload;
    },
    toggleCounter(state) {
      state.showCounter = !state.showCounter;
    },
  },
});

// 여러개의 reducer를 관리할 수 있다.
const store = configureStore({
  reducer: counterSlice.reducer,
});

export const counterActions = counterSlice.actions;

export default store;

 

import classes from "./Counter.module.css";
import { useSelector, useDispatch } from "react-redux";
import { counterActions } from "../store";

const Counter = () => {
  const counter = useSelector((state) => state.counter);
  const showCounter = useSelector((state) => state.showCounter);
  const dispatch = useDispatch();

  const toggleCounterHandler = () => {
    dispatch(counterActions.toggleCounter());
  };

  const handleIncrement = () => {
    dispatch(counterActions.increment());
  };

  const handleIncrease = () => {
    dispatch(counterActions.increase(10));
  };

  const handleDecrement = () => {
    dispatch(counterActions.decrement());
  };

  return (
    <main className={classes.counter}>
      <h1>Redux Counter</h1>
      {showCounter && <div className={classes.value}>{counter}</div>}
      <button onClick={toggleCounterHandler}>토글 카운터</button>
      <button onClick={handleIncrement}>숫자 증가</button>
      <button onClick={handleIncrease}>숫자 10 증가</button>
      <button onClick={handleDecrement}>숫자 감소</button>
    </main>
  );
};

export default Counter;

 

'React' 카테고리의 다른 글

React : react-router-dom  (0) 2024.02.28
React : Redux 비동기 처리  (0) 2024.02.27
React : Redux 사용하기  (0) 2024.02.27
React : Redux란?  (0) 2024.02.26
React : Form 유효성 검사 3가지 방식  (1) 2024.02.26