React - Redux 사용하기

프동프동·2022년 7월 10일
0

React

목록 보기
2/3
post-thumbnail

설치하기

redux core 설치하기

npm install redux

react redux 설치하기

npm install react-redux

흐름

Component -> Action -> Reducer -> Store

  1. dispatch(useDispatch)를 통해 사용자가 원하는 action을 던진다.
  2. ruducer에서 사용자가 취하는 액션에 대한 결과를 설정한다.
    • if문, switch문 이용
  3. useSelector를 통해 store에서 값을 가져온다.

react에서 Redux를 사용할 수 있도록 세팅

index.js에 Provider를 넣어준다.

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

저장할 공간 store 생성

store.js

import { createStore } from 'redux';
import reducer from './reduer/reducer';

let store = createStore(reducer);

export default store;

reducer에서 사용자가 취하는 액션에 대한 결과를 설정한다.

reducer.js

  • reducer는 항상 retern을 해줘야한다.
  • if문, switch문 조직 마다 다르다.
// 초기 값
let inititalState = {
  count: 0,
};
function reducer(state = inititalState, action) {
  // 두개의 매개변수를 받는다.
  console.log('action은 뭘까?', action);
  if (action.type === 'INCREMENT') {
    return { ...state, count: state.count + action.payload.number };
  }
  if (action.type === 'DECREMENT') {
    return { ...state, count: state.count - action.payload.number };
  }
  // switch (action.type) {
  //   case 'INCREMENT':
  //     return { ...state, count: state.count + action.payload.number };
  //   case 'DECREMENT':
  //     return { ...state, count: state.count - action.payload.number };
  //   default:
  //     return { ...state };
  // }
  return { ...state };
}

export default reducer;

useSelector()를 이용해 Store에 있는 값을 가져온다.

app.js

import { useDispatch } from 'react-redux';
import { useSelector } from 'react-redux';
import Box from './component/Box';
function App() {
  const dispatch = useDispatch();
  const count = useSelector((state) => state.count);

  const increase = () => {
    dispatch({ type: 'INCREMENT', payload: { number: 5 } });
  };

  const decrease = () => {
    dispatch({ type: 'DECREMENT', payload: { number: 3 } });
  };

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increase}>증가</button>
      <button onClick={decrease}>감소</button>
    </div>
  );
}

export default App;

결과

profile
좋은 개발자가 되고싶은

0개의 댓글