Redux 설정

개발자지망생·2023년 11월 1일
0

React

목록 보기
13/24

Redux 설정부터 사용까지!

1. Redux 설정방법

(1)Redux 설치

yarn add redux react-redux
아래와 같은 의미
yarn add redux
yarn add react-redux

(2)폴더 구조 생성

1. src 폴더 안에 redux 폴더
2.redux 폴더 안에 config, modules 폴더 생성
3.config폴더 안에configStore.js 파일 생성

폴더와 파일의 역할
redux : 리덕스와 관련된 코드를 모두 모아 놓을 폴더
config : 리덕스 설정과 관련된 파일들을 놓을 폴더
configStore : 중앙 state 관리소 인 Store를 만드는 설정들
modules : 우리가 만들 state들의 그룹

설정 코드 작성

(1)src/configStore.js


import { createStore } from "redux";
import { combineReducers } from "redux";

/*
1. createStore()
리덕스의 가장 핵심이 되는 스토어를 만드는 메소드(함수) 입니다. 
리덕스는 단일 스토어로 모든 상태 트리를 관리한다고 설명해 드렸죠? 
리덕스를 사용할 시 creatorStore를 호출할 일은 한 번밖에 없을 거예요.
*/

/*
2. combineReducers()
리덕스는 action —> dispatch —> reducer 순으로 동작한다고 말씀드렸죠? 
이때 애플리케이션이 복잡해지게 되면 reducer 부분을 여러 개로 나눠야 하는 경우가 발생합니다. 
combineReducers은 여러 개의 독립적인 reducer의 반환 값을 하나의 상태 객체로 만들어줍니다.
*/

const rootReducer = combineReducers({}); 
const store = createStore(rootReducer); 

export default store; 

(2)index.js

// 원래부터 있던 코드
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

// 우리가 추가할 코드
import store from "./redux/config/configStore";
import { Provider } from "react-redux";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(

	//App을 Provider로 감싸주고, configStore에서 export default 한 store를 넣어줍니다.
  <Provider store={store}> 
    <App />
  </Provider>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

3. 정리

  • 리액트에서 리덕스를 사용하려면 , redux,react-redux가 필요
  • '중앙 State 관리소'를 Store(스토어)라고 부른다.
  • 모듈이란, State들의 그룹
profile
프론트엔드개발자를 목표로 공부중입니다.

0개의 댓글