재우니의 블로그

react에서 많이 사용되는 상태관리 redux 에 대해 알아보기

 

redux는 react에서 많이 사용되는 상태관리를 위한 라이브러리라고 볼 수 있습니다.

redux에서 사용되는 용어는 스토어, 액션, 디스패치, 리듀서있습니다.

 

 

스토어는 상태를 가지고 있으며

컴퍼넌트디스패치 함수를 통해 액션을 리듀서로 전달하며,

상태는 리듀서에 의해서만 변경이 가능하고

컴퍼넌트는 이러한 상태를 구독하게 됩니다..

 

 

아래 코드는 생활코딩 영상을 보면서 작성한 코드 입니다. 블로그 내용 하단에 링크 기재해 두었습니다.

 

 

import React from 'react';
import './style.css';
import { createStore } from 'redux';

//상태 조회는 useSelector, 액션 생성은 useDispatch
import { Provider, useSelector, useDispatch, connect } from 'react-redux';

function reducer(currentState, action) {
  if (currentState === undefined) {
    return {
      number: 1,
    };
  }
  const newState = { ...currentState };
  if (action.type === 'PLUS') {
    newState.number++;
  }
  return newState;
}

// 위에서 만든 reducer를 스토어 만들때 넣어줍니다
const store = createStore(reducer);

export default function App() {
  // Provider : 만든 store를 앱 상위에 넣어줍니다.
  return (
    <div>
      <h1>Root</h1>
      <Provider store={store}>
        <Left1></Left1>
        <Right1></Right1>
      </Provider>
    </div>
  );
}

function Left1(props) {
  //생성한 action을 useDispatch를 통해 발생시킬 수 있다
  const dispatch = useDispatch();

  // 적용: dispatch({type:액션타입})
  return (
    <div>
      <h1>Left1</h1>
      <input
        type="button"
        value="+"
        onClick={() => {
          dispatch({ type: 'PLUS' });
        }}
      ></input>
    </div>
  );
}

function Right1(props) {
  //store에 저장된 state를 가져올 수 있는 역할
  //state를 조회하기 위한 useSelector를 사용할 수 있다
  //connect함수를 이용하지 않고 리덕스의 state를 조회할 수 있다.

  // 필요한 상태가 바뀔때만 재렌더링되게 다음과 같이 쪼개서 가져올 수 있음
  // number 가져오고 싶다면 다음과 같이 가져옵니다.
  const number = useSelector((state) => state.number);

  return (
    <div>
      <h1>Right1 : {number}</h1>
    </div>
  );
}

 

 

https://stackblitz.com/edit/react-hbmmh9?file=src/App.js 

 

React (forked) - StackBlitz

 

stackblitz.com

https://react-redux.js.org/api/hooks

 

Hooks | React Redux

API > Hooks: the `useSelector` and `useDispatch` hooks`

react-redux.js.org

https://github.com/egoing/redux-tutorial-example/blob/master/with-redux.html

 

GitHub - egoing/redux-tutorial-example

Contribute to egoing/redux-tutorial-example development by creating an account on GitHub.

github.com

https://velog.io/@qf9ar8nv/%EA%B0%84%EB%8B%A8%ED%95%9C-%EC%98%88%EC%A0%9C%EB%A5%BC-%ED%86%B5%ED%95%B4-Redux%EB%A5%BC-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0

 

간단한 예제를 통해 Redux를 이해하기

현재 진행하는 토이 프로젝트에 react + mobx를 사용하기로 했는데, 아직 react의 상태관리에 대해 이해가 잘 되지 않아서 가장 널리 알려진 redux부터 공부를 시작했습니다..😂간단한 redux 예제도 클

velog.io

https://m.blog.naver.com/wj8606/221843221092

 

React Redux 사용법 기초!

redux는 react에서 많이 사용되는 상태관리를 위한 라이브러리라고 볼 수 있다. 즉 리액트 이외에서도 사용...

blog.naver.com

 

참고 사이트 

react-redux (2022년 개정판)

 

https://www.youtube.com/watch?v=yjuwpf7VH74