
React에서 상태 관리를 할 때 가장 대표적으로 사용하는 것은 useState이다. 하지만 여러 컴포넌트에서 동일한 상태를 공유해야 하는 경우, props로 상태를 계속 내려주는 과정이 복잡해질 수 있다.
이러한 경우에는 전역 상태 관리 라이브러리를 사용하는 것이 효율적이며, 오늘은 대표적인 전역 상태 관리 라이브러리인 Redux Toolkit을 사용한 전역 상태 관리 방법에 대해 다뤄보고자 한다.
우선 기능 구현에 필요한 라이브러리를 설치한다.
npm install redux react-redux @reduxjs/toolkit
configureStore를 사용해 store를 생성하고, reducer를 등록한다.
// store.js
import { configureStore } from "@reduxjs/toolkit";
import communityReducer from "./communitySlice";
const store = configureStore({
reducer: {
community: communityReducer,
},
});
export default store;
createSlice를 사용하면 상태와 reducer를 한 번에 정의할 수 있다.
// communitySlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
activeButton: "프로젝트",
title: "프로젝트",
};
const communitySlice = createSlice({
name: "community",
initialState,
reducers: {
setActiveButton(state, action) {
state.activeButton = action.payload;
state.title = action.payload;
},
},
});
export const { setActiveButton } = communitySlice.actions;
export default communitySlice.reducer;
Provider로 감싸주면 하위 컴포넌트에서 store에 접근할 수 있다.
// index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./store";
import App from "./App";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
useSelector로 상태를 가져오고
useDispatch로 상태를 변경한다.
// CommunityPage.js
import { useSelector, useDispatch } from "react-redux";
import { setActiveButton } from "../communitySlice";
const CommunityPage = () => {
const { activeButton, title } = useSelector(
(state) => state.community
);
const dispatch = useDispatch();
const handleButtonClick = (buttonText) => {
dispatch(setActiveButton(buttonText));
};
return (
<>
<h1>{title}</h1>
<button onClick={() => handleButtonClick("프로젝트")}>
프로젝트
</button>
<button onClick={() => handleButtonClick("질문")}>
질문
</button>
<button onClick={() => handleButtonClick("블로그")}>
블로그
</button>
</>
);
};
export default CommunityPage;
유익한 정보 감사합니다~👍