Next.js Redux – Creating Application from Scratch

In this guide, you will learn how to start using Redux in the Next js application. We will explore the importance, advantages and various use cases of using Redux in the Next js application and how also explain steps to easily incorporate it from scratch using a sample application. What is Redux and Redux Toolkit?…

By.

•

min read

In this guide, you will learn how to start using Redux in the Next js application. We will explore the importance, advantages and various use cases of using Redux in the Next js application and how also explain steps to easily incorporate it from scratch using a sample application.

What is Redux and Redux Toolkit?

Redux is a predictable state container for javascript-based applications. It helps us to write applications which behave consistently and can run in different environments like client, server and native. It also helps in making the testing and maintenance process very easy. Redux helps in various ways for example:

  • Manage state across components in application areas.
  • Implementation of complex logic which includes the updating of the state.
  • Accessing the state from anywhere in the app

Whereas Redux Toolkit is the toolset for efficient Redux development for your project. It is the official, well furnished well suited for plug-and-play operation in terms to work with Redux. It includes several most used utility functions that simplify the most common use cases in Redux.

 

Advantages of Using Redux in Next.js Applications

There are a number of advantages of using Redux in Next js or any other Javascript-based application project. Here are the most common and practical of them:

Predictable State Management – We can easily manage the global state of our application which can be easily predicted manner. The flow of state can be easily tracked to diagnose when, how, why and where the state is getting changed providing full control over it.

Debugging Capabilities: Using Redux, we can easily debug complex applications by deploying Redux-powered tools. Moreover, we can travel back in time to the previous state very easily without any extra effort to easily debug the use cases.

Middleware Support: Another powerful feature is Redux support for middleware. Middleware enables the use to write asynchronous logic which can interact with the state store which allows you to write asynchronous logic that interacts with the store. This is useful for handling API calls and other side effects during data sharing.

Community and Ecosystem: Redux is a reputed ecosystem, supported by a large community and a wide range of libraries and tools for any type of feature in your application.

Server-side Rendering: Next js framework which is known and built for server-side rendering applications can easily work in sync with Redux to handle the initial render of the application on the server side. This improved the performance and SEO capabilities on your app in a bonus

 

Use Cases for Redux in Next.js Applications

Here are some of the common and mostly used cases of Redux in the Next js is when:

  • There is a large number of application states which can sit at different parts of a complex application, then Redux can help to manage the state in one place without any issues.
  • The application frequently changes states over time and has dynamic nature.
  • The logic used to update the state is complex.
  • We need a quick, consistent and accurate way to manage the application’s state and the only focus needs to be put on data rather than its maintenance.
  • In the Next.js app where pages are rendered server-side, Redux can help to avoid prop management from parent to child components. It keeps the state consistent across page transitions as well.

 

How to Add Redux in the Next js application?

Now, we will follow these few steps to easily start integration of redux in your Next js application:

Step 1: Setting Up the Project
Step 2: Install Redux and next-redux-wrapper Library
Step 3: Setup Redux Store
Step 4: Create Wrapper from Next Redux Wrapper
Step 5: Wrap MyApp Component
Step 6: Connecting to Redux Store
Step 7: Run the Application

 

Step 1: Setting Up the Project

First, we will create a new Next js application by executing the below npx command:

npx create-next-app nextjs-redux-app

 

Thereafter, enter the app directory by using the cd command:

cd nextjs-redux-app

 

Step 2: Install Redux and next-redux-wrapper Library

Now, we need to install some of the Redux-related packages in our app to easily integrate the store to manage the state.

Execute following command to install all the packages at once including redux, react-redux, next-redux-wrapper and redux toolkit.

npm install redux react-redux next-redux-wrapper @reduxjs/toolkit

 

Step 3: Setup Redux Store

At the application root, create a new file store.js, which will configure and create a Redux store.

import { configureStore } from "@reduxjs/toolkit";

export const store = configureStore({
  reducer: {
    counter: (state = 0, action) => {
      switch (action.type) {
        case "INCREMENT":
          return state + 1;
        case "DECREMENT":
          return state - 1;
        default:
          return state;
      }
    },
  },
});

The configureStore function from @reduxjs/toolkit will be used to create our store. The reducer function will handle the actions related to incrementing or decrementing the counter variable. We are also exporting the store to be used in other parts of our application.

 

Step 4: Create Wrapper from Next Redux Wrapper

Now we will create the wrapper.js file at the application root to setup the wrapper from next-redux-wrapper and update it with the following:

import { createWrapper } from "next-redux-wrapper";
import { store } from "./store";

export const wrapper = createWrapper(() => store);

 

Step 5: Wrap MyApp Component

Next, open the _app.js file and update it with the following:

import { Provider } from "react-redux";
import { store } from "../store";
import { wrapper } from "../wrapper";

function MyApp({ Component, pageProps }) {
  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  );
}

export default wrapper.withRedux(MyApp);

 

Step 6: Connecting to Redux Store

Finally, open the pages/index.js file and update the page content with the following to have increment and decrement buttons connecting with the state in the store to update the values.

import { useSelector, useDispatch } from "react-redux";

export default function IndexPage() {
  const counter = useSelector((state) => state.counter);
  const dispatch = useDispatch();

  const increment = () => {
    dispatch({ type: "INCREMENT" });
  };

  const decrement = () => {
    dispatch({ type: "DECREMENT" });
  };

  return (
    <div>
      <h1>Counter: {counter}</h1>

      <button onClick={increment}>Increment</button>

      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

 

Step 7: Run the Application

Now run the application to see the counter working using the Redux store, Execute npm run dev command to start the web server.

 

Conclusion

In this guide, we discussed how to create a new Next js app and integrate and setup the Redux store in it. We installed the required packages and libraries to make our integration and operations easy. After the we created a very simple Counter app aith Increment and Decrement actions to handle the counter value.

You can use this to kickstart your more advanced implementation of Redux Store in your app. Hope this will be helpful.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *