Redux #3 _ 다중 Slice
기본적으로 redux toolkit을 이용해서 state 공유 및 관리와 함수 사용등을 알았다.
이제 slice를 용도별로 분류하고 여러 개의 state를 사용하는 방법을 알아보자.
처음에는 store폴더에 index.js로 모든 redux 함수들을 모아놨었지만
지금은 용도별로 분류했다.
여기서 사용한 것은 counter와 auth 이다.
1. auth
import { createSlice } from "@reduxjs/toolkit";
const initlAuthState = { isAuthenticated: false };
const authSlice = createSlice({
name: "auth",
initialState: initlAuthState,
reducers: {
login(state) {
state.isAuthenticated = true;
},
logout(state) {
state.isAuthenticated = false;
},
},
});
export const authActions = authSlice.actions;
export default authSlice.reducer;
2. counter
import { createSlice } from "@reduxjs/toolkit";
const initialCounterState = { counter: 0, showCounter: true };
const counterSlice = createSlice({
name: "counter",
initialState: initialCounterState,
reducers: {
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
},
increase(state, action) {
state.counter = state.counter + action.payload;
},
toggleCounter(state) {
state.showCounter = !state.showCounter;
},
},
});
export const counterActions = counterSlice.actions;
export default counterSlice.reducer;
이런 식으로 같은 원리로 두 가지의 함수로 나눠서 사용할 수 있다.
이제 이 2가지를 한 번에 관리할 수 있도록 index.js를 관리하였다.
3. index.js
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counter";
import authReducer from "./auth";
const store = configureStore({
reducer: { counter: counterReducer, auth: authReducer },
});
export default store;
두 가지에서 import 해서 index에서 store 해서 사용했다.
이제 이 위의 값을 사용하기 위한 방법이다.
일단 루트 파일에서 store를 공유하기 위해서 아래와 같은 방법으로
store를 공유하였다. useContext의 provider와 같은 원리이다.
import React from "react";
import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import "./index.css";
import App from "./App";
import store from "./store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<App />
</Provider>
);
내가 하고자 한 것은 로그인/로그아웃 auth 상태의 true/false 값을 토대로 해당 페이지를 보여주고 안보여주고, 헤더를 보여주고 안보여주고를 가지고 연습했다.
아래와 같은 방법으로 auth의 state 상태를 가져와서 사용했다.
import Counter from "./components/Counter";
import { Fragment } from "react";
import Headers from "./components/Header";
import Auth from "./components/Auth";
import { useSelector } from "react-redux";
import UserProfile from "./components/UserProfile";
function App() {
const isAuth = useSelector((state) => state.auth.isAuthenticated);
return (
<Fragment>
<Headers />
{!isAuth && <Auth />}
{isAuth && <UserProfile />}
<Counter />
</Fragment>
);
}
export default App;
그리고 로그인 페이지를 예로 들어서 로그인 버튼을 누르면 해당 값을 액션을 통해 트리거해서
true 값을 false로 바꾸는 작업을 했다.
import classes from "./Auth.module.css";
import { useDispatch } from "react-redux";
import { authActions } from "../store/auth";
const Auth = () => {
const dispatch = useDispatch();
const loginHandler = (event) => {
event.preventDefault();
dispatch(authActions.login());
};
return (
<main className={classes.auth}>
<section>
<form>
<div className={classes.control}>
<label htmlFor="email">Email</label>
<input type="email" id="email" />
</div>
<div className={classes.control}>
<label htmlFor="password">Password</label>
<input type="password" id="password" />
</div>
<button onClick={loginHandler}>Login</button>
</form>
</section>
</main>
);
};
export default Auth;
다른 로직은 제외하고 state의 값을 변경하고 사용하는 것에 초점을 맞췄다.
사용법은 의외로 아주 간단했다.
이미 여러 개의 팀 프로젝트를 마치고도 Redux라는 것에 대한 자세한 이해도가 없었던 게 느껴진다.
물론 생애 첫 코딩을 하면서 짧은 시간에 많은 지식을 넣어야 했기 때문도 있지만
이제야 Redux를 왜 사용하고 어떻게 사용하는지에 대한 이해가 조금 생겼다.