웹
Redux Toolkit 으로 상태 관리하기
sleedev
2024. 1. 17. 20:04
전역상태 관리가 필요한 이유
리액트에서는 상태를 통해서 UI에 있는 정보를 업데이트하고 쉽게 렌더링 할 수 있는데
아무 상태나 막 생성하다보면,, 한 함수 안에서 엄청 여러개의 상태값을 변경하고 있는 걸 볼 수가 있다.
그리고 상태값을 사용하거나 상태값을 세팅하기 위해서
자식컴포넌트로 계속 내려주는 일이 생길 수도 있다.
그런 문제점을 차단하기 위해서 많이 쓰이는 전역 상태들은 여러 라이브러리로 관리할 수가 있다.
여기에서는 리덕스로 관리하는 법에 대해서 정리를 해보고자 한다.
사용법
1. createSlice()
const { createSlice } = require('@reduxjs/toolkit')
리덕스의 메서드로, 이니셜 상태, 리듀서 함수 객체, 슬라이스 이름 등의 정보를 받아 슬라이스를 만든다.
/** /src/redux/slice/AuthSlice.js */
const { createSlice } = require('@reduxjs/toolkit')
const initialState = {
isLoggedIn: false,
userId: null,
}
const authSlice = createSlice({
// 액션 타입에서 쓰이게 될 이름을 설정한다.
name: 'auth',
// 리듀서의 초기값을 설정한다.
initialState,
// string: 키값, function: 액션 함수
reducers: {
SET_ACTIVE_USER: (state, action) => {
const { email, userName, userId } = action.payload
state.isLoggedIn = true
state.userId = userId
},
REMOVE_ACTIVE_USER: (state) => {
state.isLoggedIn = false
state.userId = null
},
},
})
// 위에서 만들어진 슬라이스의 액션을 키값으로 참조할 수 있도록 export
export const { SET_ACTIVE_USER, REMOVE_ACTIVE_USER } = authSlice.actions
// 컴포넌트에서 값을 참고하고자 할 때 useSelector((state) => state.auth.isLoggedIn)
// 위처럼 써야하지만 이렇게 함수로 export 하면 useSelector(selectIsLoggedIn)
// 와 같이 간편하게 사용할 수 있다.
export const selectIsLoggedIn = (state) => state.auth.isLoggedIn
export const selectUserId = (state) => state.auth.userId
// 슬라이스의 리듀서를 기본적으로 export
export default authSlice.reducer
2. configureStore()
루트 리듀서로 각각의 슬라이스 리듀서를 통합해준다. 그렇게 되면 리덕스 개발툴에서 사용하기 용이하다.
그리고 그 상태에 대해 설정을 한 후에 상태를 export한다.
import { combineReducers, configureStore } from '@reduxjs/toolkit'
import authReducer from './slice/authSlice'
const rootReducer = combineReducers({
auth: authReducer,
})
const store = configureStore({
reducer: rootReducer,
})
export default store
3. Provider 컴포넌트 만들기
Provider 컴포넌트에 store 속성에 위에서 만든 store를 넣어주고
최상단 (그 상태값을 사용하기 위한 가장 최상단의 위치)에 넣어주면 그 아래의 컴포넌트에서
전역 상태에 접근이 가능하다.
'use client'
import React from 'react'
import { Provider } from 'react-redux'
import store from './store'
const Providers = ({ children }) => {
return <Provider store={store}>{children}</Provider>
}
export default Providers
4. 컴포넌트에서 사용하기
useDispatch 훅을 통해서 dispatch를 만들어 주고, 취하고자 하는 액션 함수의 키값을 적은 후에 매개 변수를 맞게 작성해준다.
dispatch는 액션을 취할 때만 사용하고, 값만 사용하고자 한다면 아래 같이 사용한다.
import { useDispatch, useSelector } from 'react-redux'
import { selectIsLoggedIn } from '@/redux/slice/productSlice'
const dispatch = useDispatch()
dispatch(
SET_ACTIVE_USER({
email: user.email,
userName: displayName,
userId: user.uid,
}),
)
const isLoggedIn = useSelector(selectIsLoggedIn)