0

3 Effective Ways To Implement State Management In Next.js

 1 year ago
source link: https://blog.bitsrc.io/3-effective-ways-to-implement-state-management-in-next-js-66d1b09f0b8b
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

3 Effective Ways To Implement State Management In Next.js

0*yoynEIs-AQnwG3E_.png

State management plays a vital role in any modern web application. The reason is that state helps to determine what data is rendered on the screen during the app usage session while the user working with it.

In this article, we are going to discuss different state management methods that we can use with a Next.js web app I will give a practical example for each method so you can evaluate them better.

How does state work?

A JavaScript object that holds the current status of the data is called a state. You can think of it as a car switch that can have either “on” or “off” states. Now, transfer the same principle to the React ecosystem and imagine the use of the light and dark mode toggle. We should always keep one thing in our mind the state must always be passed down from the parent element to the children elements.

File Structure Of Next.js

As we know Next.js is a framework that is built on the top of the React, it has a specific file structure. To understand different ways of state management, we first need to understand how the Next.js file system is built.

First of all, you run npx create-next-app project-name in your terminal, it will generate a fully working Next.js application that contains 4 main blocks: root level, then the pages, public, and styles folders in it.

For the purpose of managing the state, we are going to use pages and the two files inside it: _app and index.js. The _app file is the root file for the whole application. The index.js file is for the Home component.

Using the useState Hook for managing state in Next.js

The useState Hook is one of the most common ways to manage the state in Next.js. We will build an application that lets you increase the count by clicking the button.

Go to pages and include the code given below in index.js:

We first imported the useState hook, then declare the initial state to be 0. We also provided a setCount function so we can update the count later.

Then we made the function increaseCount, which accesses the current value of the count and uses setState to increase that by 1.

We provided the function to the onClick event for the plus button, so each time the button is pressed, the score increases.

State Management By Using The useReducer Hook

The useReducer Hook works likewise to the reduce method for arrays. A reducer function and an initial value are passed by us. The reducer takes the current state and an action and returns the new state.

We are going to create an app that lets you add the currently active result by 2. Include the below-given code in index.js:

We imported the useReducer Hook first. We provided the reducer function and the initial state.

The Hook then returned an array of the current state and the dispatch function.

We gave the dispatch function to the onClick event so that the current state value gets added by 2 each time the button is clicked, setting it to the following values: 4, 6, 8, 10, 12, and so on.

State Management By Using The Context API Hook

Many use cases for most of the basic apps you build will be covered with help of useState and useReducer Hooks but what if your app is way more complex, the props need to be given down multiple levels, or you have some states that need to be accessible globally?

Well, the solution is to use Context API, which allows you to access the state globally. It’s considered good practice to develop separate contexts for different states like authentication, user data, and so on.

We will develop an example for theme state management.

First of all, create a separate folder in the root and call it context. Inside it create a new file called theme.js and include the code given below:

First of all, created a new Context object, created a function with the name of ThemeProvider, and put the initial value for the Context to light. Then, we developed a custom useThemeContext Hook that will help us to get the theme state after we import it into the individual pages or components of our app.

Next, we have to wrap the ThemeProvider around the entire app, so we can get the state of the theme in the whole application. Go to the _app.js file and include the code given below:

To get the state of the theme, go to index.js and include the code given below:

First of all, useThemeContext is imported, then got the theme state and the setTheme function change the state whenever needed. Inside the onClick event of a toggle button, we made an update function that switches between the opposite values between light and dark, based on the current value.

Conclusion

In this tutorial, we created many mini-applications to demonstrate many of the ways of state management in Next.js apps. In each case, we have implemented different state management solutions, but the great challenge in picking the most suitable state management solution is the capability to identify what states you need to track.

Novices frequently struggle and choose overkill solutions for simple state management, but it gets improved with time, and the only way to improve it is by practicing.

Hopefully, this article helped you to take a step in the right direction towards achieving that.

Bit: Build Better UI Component Libraries

Say hey to Bit. It’s the #1 tool for component-driven app development.

With Bit, you can create any part of your app as a “component” that’s composable and reusable. You and your team can share a toolbox of components to build more apps faster and consistently together.

  • Create and compose “app building blocks”: UI elements, full features, pages, applications, serverless, or micro-services. With any JS stack.
  • Easily share, and reuse components as a team.
  • Quickly update components across projects.
  • Make hard things simple: Monorepos, design systems & micro-frontends.

Try Bit open-source and free→

1*p3UFa6xnmmbrkTzfRm_EmQ.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK