ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React(tsx)에서의 Redux 초기 세팅
    기타/메모장 2022. 10. 28. 13:20

    NPM

    npm i redux
    npm i react-redux
    npm i @reduxjs/toolkit

    redux.tsx

    import { configureStore, createAction, createReducer } from "@reduxjs/toolkit";
    
    export interface IReduxStore {
      value: number;
    }
    
    const initState: IReduxStore = {
      value: 0,
    };
    
    export const addValue = createAction<number>("ADD");
    export const increment = createAction("increment");
    export const decrement = createAction("decrement");
    
    const myReducer = createReducer(initState, (builder) => {
      builder
        .addCase(addValue, (state, action) => {
          state.value += action.payload;
        })
        .addCase(increment, (state) => {
          state.value++;
        })
        .addCase(decrement, (state) => {
          state.value--;
        });
    });
    
    export default configureStore({
      reducer: myReducer,
    });

    index.tsx (React)

    import React from "react";
    import ReactDOM from "react-dom/client";
    import { Provider } from "react-redux";
    import redux from "./redux";
    
    const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
    root.render(
      <React.StrictMode>
        <Provider store={redux}>
          <App />
        </Provider>
      </React.StrictMode>
    );

    Usage

    import { shallowEqual, useDispatch, useSelector } from "react-redux";
    import { IReduxStore, RSetValue } from "../redux";
    
    const dispatch = useDispatch()
    const value1 = useSelector<IReduxStore, number>((state) => {
      return state.value1;
    }, shallowEqual);
    
    const value1Handler = (value: number) => {
      dispatch(RSetColor(value));
    }

    댓글