State Management with Redux

This guide provides a step-by-step tutorial on setting up state management in a Next.js project using Redux Toolkit with Redux Persist.

1. Install Dependencies

Run the following command to install Redux Toolkit and Redux Persist:

npm install @reduxjs/toolkit react-redux next-redux-wrapper 
2. Configure Redux Store

Create a Redux store with persistence in src/redux/store.ts:

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()
3. Create a Redux Slice

Define a simple counter slice in src/redux/slices/counterSlice.ts:

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;
5. Provide the Store in Main.tsx

Wrap the application with the Redux Provider in src/main.tsx:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import { Provider } from "react-redux";
import store from "./slices/reducer.ts";
import { BrowserRouter as Router } from "react-router-dom";
             
createRoot(document.getElementById("root")!).render(
  
      <Provider store={store}>
          <Router basename={import.meta.env.BASE_URL}>
             <App/>
          </Router>
      </Provider>
  ,
    );
6. Use Redux State in a Component

Use the Redux state in a component like Counter.tsx:

'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>
); }
Receive the latest updates directly in your inbox!

Be the first to know about new updates and exclusive discounts. No spam, just great offers!

How about

A Custom Project?

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 Admin & Dashboards
230+

Total Pages

5+

Layouts

11+

Application

We provide quick support withing one business day to all of our customers.

© Domiex Created & Crafted by SRBThemes.