[TIL] React - store

JongYeon·2025년 2월 4일

TIL

목록 보기
33/69
post-thumbnail

store

store는 전역 상태 관리를 할 수 있게 관리해주는 중앙 관리소

store 사용 방법

1. rootReducer를 생성한다.

/src/redux/config/configStore.js

const { combineReducers } = require("redux");

const rootReducer = combineReducers({});

2. store를 생성하고 내보낸다.

/src/redux/config/configStore.js

const { combineReducers, createStore } = require("redux");

const rootReducer = combineReducers({});

const store = createStore(rootReducer);

export default store;

3. main.jsx에서 Provider를 설정한다.

/src/main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.jsx";

//새로운 코드
import { Provider } from "react-redux";
import store from "./redux/config/configStore.js";

//store로 App을 감싸므로, store로 전역 상태 관리를 하겠다고 선언한다.
createRoot(document.getElementById("root")).render(
  <StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </StrictMode>
);

4. 모듈을 만든다.

/src/redux/modules/counter.js

//state의 초기값
const initialState = {
  number: 0,
};

//reducer는 state와 action 2개의 인자를 갖는다. 
//action은 객체 형태로 존재하며 type과 payload를 갖는다.
//switch문을 통해 dispatch가 case를 선택해 사용한다.
const counter = (state = initialState, action) => {
  switch (action.type) {
    default:
      return state;
  }
};

export default counter;

5. store에 모듈 연결

/src/redux/config/configStore.js

import counter from "../modules/counter";

const { combineReducers, createStore } = require("redux");

const rootReducer = combineReducers({
  counter: counter,
});

const store = createStore(rootReducer);

export default store;

6. state 조회

객체 형태의 state가 출력

counter: {number:0}

우리는 컴포넌트에서 스토어를 조회할 때

react-redux에서 제공하는 useSelector 라는 훅을 사용한다. (중요 🔥)

화살표 함수에서 꺼낸 state라는 인자는 모든 리덕스 모듈의 최상위 객체를 의미하는 Root State다.

reducer

변화를 일으키는 함수

리듀서는 useState에서 상태 변경 함 함수 역할을 한다.
인자로는 state와 action을 갖는다. state = intialState 처럼 stateinitialState를 할당 하는 것을 기억해야한다.

하루를 마치며

오늘은 개인 과제 2일차다. 2일차만에 막히는 구간이 와서 힘든 시간이였다. 어떻게든 기능을 완성해내고야 말 것이다. 기능을 스스로 만들면서 성취감을 느껴보고 싶다. 항상 답답한 마음밖에 없었는데 이번 과제에서는 느끼고 싶다.

profile
프론트엔드 공부중

0개의 댓글