The Redux toolkit is recommended for handling the global state in Next.js. It sets up the Redux with minimal boilerplate and provides integrated support for immutability and async actions.
To install, run @reduxjs/toolkit, and react-redux:
npm install @reduxjs/toolkit react-redux
The store combines the reducers and allows the Redux DevTools to debug.
import { configureStore } from "@reduxjs/toolkit";
import taskReducer from "./slices/taskSlice"; // Import reducer
export const store = configureStore({
reducer: {
tasks: taskReducer, // Register slice reducer under "tasks"
},
devTools: process.env.NODE_ENV !== "production",
});
configureStore allows you to set up the store without any challenges.
taskReducer holds the task-related state.
A slice manages the state and actions relevant to a feature.
import { createSlice } from "@reduxjs/toolkit";
const taskSlice = createSlice({
name: "tasks",
initialState: { tasks: [] },
reducers: {
addTask: (state, action) => {
state.tasks.push(action.payload); // Immutable handling via Immer
},
},
});
export const { addTask } = taskSlice.actions;
export default taskSlice.reducer;
Wrap your app with a Provider as the way to expose Redux to all components.
"use client";
import { Provider } from "react-redux";
import { store } from "@/lib/store";
export function Providers({ children }: { children: React.ReactNode }) {
return <Provider store={store}>{children}</Provider>;
}
Provider provides access to Redux state to all child components.
Store will be passed to Provider as a prop.
Wrap your application inside Provider in layout.tsx.
import { Providers } from "@/lib/providers";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}
useDispatch is used to dispatch an action to change state.
"use client";
import { useAppDispatch } from '@/lib/store';
import { addTask } from '@/lib/slices/taskSlice';
export default function Home() {
const dispatch = useAppDispatch();
return (
<button onClick={() => dispatch(addTask({ id: 1, text: "Learn Redux" }))}>
Add Task
</button>
);
}
useSelector is a hook for returning state.
"use client";
import { useSelector } from "react-redux";
import { RootState } from "@/lib/store";
export default function TaskList() {
const tasks = useSelector((state: RootState) => state.tasks.tasks);
return (
<ul>
{tasks.map(task => (
<li key={task.id}>{task.text}</li>
))}
</ul>
);
}
useSelector picks out a slice of the application state.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.