Redux 상태관리

j moon·2022년 9월 1일
0

Redux

동작 순서

1.action
2.dispatch
3.reducer
4.store

구현 순서

  1. Store
  2. Reducer
  3. Action
  4. useDispatch
  5. useSelector

실습

+,- 버튼을 눌렀을때 count 가 1씩 늘어나게 redux로 상태관리

  • 파일구조

1-1. Reducers에서 사용할 state 를 선언해준다.

// initialState.js
export const initialState = 1;

1-2. Actions - index.js 에서 state 변경시 처리할 dispatch 정의

// Actions/index.js
export const INCREASE = 'INCREASE';
export const DECREASE = 'DECREASE';

export const increase = () => {
  return {
    type: INCREASE,
  };
};

export const decrease = () => {
  return {
    type: DECREASE,
  };
};

1-3. Reducers - index.js 에서 dispatch 후 처리할 reducer 정의

// Reducers/index.js
import { initialState } from './initialState.js';
import { INCREASE, DECREASE, increase, decrease } from '../Actions';

export const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case INCREASE:
      return state + 1;
    case DECREASE:
      return state - 1;
    default:
      return state;
  }
};

1-4. Store에 Reducer 연결

// Store/index.js
import { legacy_createStore as createStore } from 'redux';
import { counterReducer } from '../Reducers';

export const store = createStore(counterReducer);

1-5. 최상위 index.js에서 store 정의

// index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import { store } from './Store';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

1-6. App.js 에서 store에 있는 state 사용

//App.js
import React from 'react';
import './style.css';
import { useSelector, useDispatch } from 'react-redux';
import { increase, decrease } from './Actions';

export default function App() {
  const dispatch = useDispatch();
  const state = useSelector((state) => state);
  const plusNum = () => {
    dispatch(increase());
  };

  const minusNum = () => {
    dispatch(decrease());
  };

  return (
    <div className="container">
      <h1>{`Count: ${state}`}</h1>
      <div>
        <button className="plusBtn" onClick={plusNum}>
          +
        </button>
        <button className="minusBtn" onClick={minusNum}>
          -
        </button>
      </div>
    </div>
  );
}

결과

profile
자발개보초

0개의 댓글