How to use State Management in Next JS Framework?

Last updated on September 7, 2022

State management is basically a plain JavaScript object holding the application’s information like action, inputs, user sessions, component rendering information, and retrieving data from the database.

State management helps us to track the user’s action on the application, for example, the user clicks on add to cart button, and the cart shows one item added by the user.

So in the application, we have to maintain the state globally using different third-party libraries on different platforms. For example, in Vue JS  most people use Vuex for state management, and in react js Redux is being used for state management.

How does State work in Next JS?

As mentioned at the beginning of the article, a state is a JavaScript object which holds the application data. we use this data as per user action, for example, a light turns on and off through the switch button. We collect the new information by on click the event and updating it with the previous one.

Each time when a user clicks on a button, toggle, or submits a field we update the state, and in the end, we send it back-end server for the process.

State Hook

Next Js framework has its own state management hook with the name of useState. We need to import it first into our file and below is the code that imports in the file.

import { useState } from "react";

For understanding, we are going to create a function that will simply increase the value of the score variable on-click event.

import { useState } from "react";

export default function Home() {
  const [score, setScore] = useState(0);
  const increaseScore = () => setScore(score + 1);

  return (
      <p>Your score is {score}</p>
      <button onClick={increaseScore}>Add Count</button>

In the above example we imported the useState hook first. Then assigned a value that is 0. We also created a setScore function so we can update the score later. Next, we created a function increaseScore that will update the useState hook after increasing the score variable value by 1 on the click event.

Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts