This guide provides a step-by-step tutorial on setting up state management in a Next.js project using Redux Toolkit with Redux Persist.
Run the following command to install Redux Toolkit and Redux Persist:
npm install @reduxjs/toolkit react-redux next-redux-wrapper
Create a Redux store with persistence in src/redux/store.js
:
import { configureStore } from '@reduxjs/toolkit'; import rootReducer from './rootReducer'; import counterReducer from './slices/counterSlice'; import { HYDRATE } from 'next-redux-wrapper' const rootReducer = combineReducers({ counter: counterReducer, }); const reducer = (state, action) => { if (action.type === HYDRATE) { const nextState = { ...state, ...action.payload, } return nextState } else { return rootReducer(state, action) } } export const makeStore = () => configureStore({ reducer, }) const store = makeStore()
Define a simple counter slice in src/redux/slices/counterSlice.js
:
import { createSlice } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: (state) => { state.value += 1; }, decrement: (state) => { state.value -= 1; }, }, }); export const { increment, decrement } = counterSlice.actions; export default counterSlice.reducer;
Wrap the application with the Redux Provider in src/app/providers.jsx
:
'use client'; import { Provider } from 'react-redux'; import { store } from '../redux/store'; export default function Providers({ children }) { return (
{children} ); }
Use the Redux state in a component like Counter.jsx
:
'use client'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement } from '../redux/slices/counterSlice'; export default function Counter() { const count = useSelector((state) => state.counter.value); const dispatch = useDispatch(); return (
); }Counter: {count}
<button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button>
Be the first to know about new updates and exclusive discounts. No spam, just great offers!
How about
With over 7 years of experienced team, we specialize in delivering custom projects for startups, blue-chip companies, and government agencies. We have successfully completed over 250+ projects, providing tailored solutions that meet the unique needs of each client.
Hire Us© Domiex Created & Crafted by SRBThemes.