-
23.06.21)Redux 리덕스란?썽이의 개발 일지/TIL 2023. 6. 21. 21:23
📌Redux란?
: <중앙 state 관리소>를 사용할 수 있게 도와주는 패키지(라이브러리)
- 리덕스는 전역상태 관리 라이브러리
- 리덕스는 중앙 State 관리소를 가지고 있으며, 모든 State는 이곳에서 생성
- useState로 생성한 State는 Local State이고, 리덕스에서 생성한 State는 Global State이다.
✅ 리덕스를 사용하면State를 공유하고자 할때 부-모 관계 컴포넌트를 거치지 않아도 된다.
▷컴포넌트가 어디에 위치하고 있든 상관없이 State를 불러와서 사용
👉 리덕스 설치 명령어
yarn add redux react-redux
👉리덕스 설정 순서
1. 리덕스 패키지 설치
2. 폴더구조 생성
src폴더 > redux폴더 >config, modules 폴더
3.파일 생성
ㆍconfig 폴더 > configStore.js (중앙 state 관리소)
ㆍmodules 폴더 > (State들의 그룹)- redux 폴더: 리덕스 관련코드 몰아넣기
config 폴더: 리덕스 설정 관련 파일 전부
configStore.js: 중앙 state 관리소
modules 폴더: state의 그룹
👉코드 작성법
1. src / config / configStore.js
//중앙 데이터 관리소(store)를 설정하는 부분 import { createStore } from "redux"; import { combineReducers } from "redux"; const rootReducer = combineReducers({}); const store = createStore(rootReducer); export default store;
- createStore( )
▷리덕스의 가장 핵심이 되는 스토어를 만드는 메소드(함수)
▷리덕스는 단일 스토어로 모든 상태 트리를 관리한다
(리덕스를 사용할 시 creatorStore를 호출은 딱 한번) - combineReducers( )
▷리덕스는 action —> dispatch —> reducer 순으로 동작한다
이때 애플리케이션이 복잡해지게 되면 reducer 부분을 여러 개로 나눠야 하는 경우가 발생하는데
combineReducers은 여러 개의 독립적인 reducer의 반환 값을 하나의 상태 객체로 만들어준다.
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();
- store와 Provider를 import해야한다
'썽이의 개발 일지 > TIL' 카테고리의 다른 글
23.06.23) React 모달 만들기 (0) 2023.06.23 23.06.22) React Router Dom 패키지 (0) 2023.06.22 23.06.20) React Hooks (1)- useState, useEffect (0) 2023.06.20 23.06.19) React-styled Components(전역 스타일링) (0) 2023.06.19 23.06.16) React를 이용해서 Todo List 만들기(3) (0) 2023.06.16