How to setup Redux toolkit in NextJS
Today I will show you how to set up the Redux toolkit in NextJS. In my previous tutorial, I have already explained How to set up Redux in NextJS but this time It’ll be Redux toolkit. Redux and Redux Toolkit are related, but they serve different purposes and have different approaches to managing the state in a React application.
Redux
Redux is a predictable state container for JavaScript applications. It is a state management library that helps you manage the global state of your application in a more organized and predictable way. Redux follows the Flux architecture and is commonly used with React, although it can be used with other frameworks as well.
Key concepts in Redux:
Store: The single source of truth that holds the entire application state.
Actions: Plain JavaScript objects that represent events or changes in the application.
Reducers: Pure functions that specify how the state changes in response to actions.
Middleware: Functions that can intercept and process actions before they reach the reducers.
Redux provides a very minimalistic and powerful API, but setting up Redux and managing boilerplate code for actions and reducers can become cumbersome in large applications. This is where Redux Toolkit comes into play.
Redux Toolkit
Redux Toolkit is the official recommended way of writing Redux logic. It is an opinionated, batteries-included package that simplifies the usage of Redux by abstracting away the common patterns and providing utilities for common tasks. Redux Toolkit is built on top of Redux and includes features like “createSlice” and “configureStore” that streamline the process of setting up Redux.
Key features of Redux Toolkit:
createSlice: A function that generates a slice of the Redux state, including the reducer and action creators. It significantly reduces the boilerplate code.
configureStore: A function to create the Redux store with sensible defaults, including support for Redux DevTools and Thunk middleware.
immer: Redux Toolkit uses Immer under the hood to enable writing reducers that directly modify the state in a more concise and readable way.
Additional utilities: Redux Toolkit also provides utilities for creating asynchronous actions using the “createAsyncThunk” function.
In summary, Redux is the core state management library, while Redux Toolkit is a set of utilities and best practices that make working with Redux easier and more efficient. Redux Toolkit simplifies the Redux setup process, reduces boilerplate code, and encourages writing cleaner and more maintainable code. If you’re starting a new Redux-based project or looking to simplify your existing Redux codebase, Redux Toolkit is the recommended choice.
Requirements
Step 1: Create a new Next.js project
Create a new Next.js project by running the below command and following the instruction on the terminal.
npx create-next-app redux-toolkit-nextjs
Step 2: Install Redux Toolkit and react-redux
npm install @reduxjs/toolkit react-redux
Step 3: Create a Redux slice file
In Redux Toolkit, slices are used to define parts of the Redux state and reducers so open your project directory and inside the src folder create a directory with the name store and inside that directory create a directory with the name slices, here we can keep all our slices file and then create a file with the name inputSlice.js and paste the below code.
import { createSlice } from "@reduxjs/toolkit";
export const inputSlice = createSlice({
// Name of our slice which we will call in our store
name: "input",
// Initial state
initialState: {
value: "",
},
// Our method inside reducers to change our state value
reducers: {
inputHandler: (state, action) => {
state.value = action.payload;
},
},
});
// Exporting our method to be called in the component
export const { inputHandler } = inputSlice.actions;
Step 4: Create the Redux store
Now inside our store folder which we have created in step 3 create a file with the name store.js and paste the below code inside the file.
import { configureStore } from "@reduxjs/toolkit";
import { inputSlice } from "@/store/slices/inputSlice";
// Creating our store and combining all slices
export const store = configureStore({
reducer: {
[inputSlice.name]: inputSlice.reducer,
},
devTools: true,
});
Step 5: Wrap your Next.js _app with the Redux Provider
Inside your src directory create a folder with the name pages (If it’s not there or you haven’t created it yet) and inside that pages directory create a file _app.js and paste the below code.
import { Provider } from "react-redux";
import { store } from "@/store/store";
function MyApp({ Component, pageProps }) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
export default MyApp;
*Note: You need to delete page.js from your app directory to render our pages from pages directory.
Step 6: Now open your redux devtool and check the initial state. If you haven't installed redux devtool install it from here for Chrome.
Step 6: Access and use the Redux state in your components
To access and use the redux state in your component we will create a simple text box which whose text will be displayed in another component.
Create a file name index.js inside the pages directory and paste the below code.
import { useDispatch } from "react-redux";
import { inputHandler } from "@/store/slices/inputSlice";
import { useState } from "react";
import DisplayComponent from "./display";
function HomePage() {
const [name, setName] = useState("");
const dispatch = useDispatch();
const handleInput = (e) => {
setName(e.target.value);
};
return (
<div>
<DisplayComponent />
<input value={name} type="text" onChange={handleInput} />
<button
onClick={() => {
dispatch(inputHandler(name));
setName("");
}}
>
Submit
</button>
</div>
);
}
export default HomePage;
Also, create a file with the name display.js and paste the below code. This file will display our text coming from the Redux store.
import React from "react";
import { useSelector } from "react-redux";
const DisplayComponent = () => {
const inputText = useSelector((state) => state.input.value);
return (
<div>
<h1>Text: {inputText}</h1>
</div>
);
};
export default DisplayComponent;
We’ve created a basic input text box that, when changed, calls the handleInput method, which changes the text we’re typing inside the box to the local state name. There is a button that on click submitting the text to our inputHandler method which we are importing from our slice file through Redux dispatch. Now if we check our Redux devtool the state will be changed from empty to the value we had in our input box and will be displayed in our display component.
That’s all! Now that you’ve integrated Redux Toolkit in your Next.js project, you may use the Redux state and actions in any component throughout your app.
Keep in mind that the file and folder structure can change based on your preferences or project requirements, but the basic steps for integrating Redux Toolkit with Next.js remain the same.
For any query, you can get in touch with me via LinkedIn
Below you can find the sample GitHub Repository and Codesandbox demo.