React Redux 패키지 설치하기
React Redux를 사용하려면 먼저 npm을 사용하여 React Redux 패키지를 설치해야 합니다.
$ npm install react-redux
Redux 패키지 설치하기
React Redux는 Redux 라이브러리를 사용합니다. 따라서 Redux 패키지도 설치해야 합니다.
$ npm install redux
React Redux를 사용하는 방법은 다음과 같습니다.
Provider 컴포넌트로 앱 감싸기
React Redux에서 제공하는 Provider 컴포넌트로 앱 전체를 감싸야 합니다. 이 컴포넌트는 Redux 스토어를 앱에 제공합니다.
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
Reducer 만들기
import { createStore } from 'redux';
const initialState = {
  myValue: 0
};
function reducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return {
        ...state,
        myValue: state.myValue + 1
      };
    case 'DECREMENT':
      return {
        ...state,
        myValue: state.myValue - 1
      };
    default:
      return state;
  }
}
const store = createStore(reducer);
Connect 함수로 컴포넌트 연결하기
Redux 스토어의 상태나 액션 생성자를 컴포넌트에 전달하려면 connect 함수를 사용해야 합니다.
import { connect } from 'react-redux';
function MyComponent(props) {
  // ...
}
function mapStateToProps(state) {
  return {
    myValue: state.myValue
  };
}
function mapDispatchToProps(dispatch) {
  return {
    myAction: () => dispatch({ type: 'MY_ACTION' })
  };
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(MyComponent);connect 함수는 두 개의 매개변수를 받습니다. mapStateToProps 함수는 스토어의 상태를 컴포넌트의 props로 매핑하는 역할을 합니다. mapDispatchToProps 함수는 액션 생성자를 컴포넌트의 props로 매핑하는 역할을 합니다.
이제 MyComponent 컴포넌트에서 myValue prop과 myAction prop을 사용할 수 있습니다.
이러한 단계를 따라 React Redux를 설치하고 사용할 수 있습니다.
실제 사용 :
import { useDispatch } from 'react-redux';
function MyComponent() {
  const myValue = useSelector(state => state.myValue);
  const dispatch = useDispatch();
  const handleIncrement = () => {
    dispatch({ type: 'INCREMENT' });
  };
  return (
    <div>
      <div>{myValue}</div>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}

'프론트 React' 카테고리의 다른 글
| React) input type file에서 같은 파일 선택에도 onChange 작동시키기 (0) | 2023.03.31 | 
|---|---|
| React) kakao map 객체 Redux로 관리 & 거리 재기 기능 추가 (0) | 2023.03.25 | 
| React) Kakao map 연동 및 현재 위치 가져오기 (0) | 2023.03.25 | 
| React-Redux) useSelector 사용 방법과 connect 차이점 (0) | 2023.03.25 | 
 
                    
                   
                    
                  