How to Use useState() Hook in NextJS?

What is the useState Hook?

In React (which Next.js is built upon), the useState hook is a built-in function that allows you to manage state within functional components. State refers to data that can change over time, influencing how your component behaves and renders.

How to Use useState in Next.js

Here’s a breakdown of using useState in a Next.js component:

Import the Hook:

Begin by importing useState from the react library at the top of your functional component:

import { useState } from 'react';

Declare State Variables:

Inside your component, use useState to declare state variables. This returns an array containing two elements:

  • The current state value (often named descriptively, like count or isLoggedIn).
  • A function to update the state (usually named setCount or setIsLoggedIn).

Here’s the basic syntax:

const [stateVariable, setStateFunction] = useState(initialState);
  • initialState: The initial value you want to assign to the state variable. This can be a number, string, object, or an array.

For example, to create a counter that starts at 0:

const [count, setCount] = useState(0);

Use the State Variable:

Access the current state value directly using the state variable name (e.g., count in the counter example) within your component’s JSX to display or use the data in your UI.

Update the State:

  1. Never modify the state variable directly. To update the state, call the setter function (e.g., setCount in the counter example) and provide the new state value or a function that calculates the new value based on the previous state.
  2. Here’s how you might increment the counter:
  3. JavaScript
<button onClick={() => setCount(count + 1)}>Increment</button>

Example: Counter Component

Here’s a complete Next.js component that demonstrates using useState for a counter:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;

In this example:

  • The useState hook is used to create a state variable count with an initial value of 0.
  • The count value is displayed in a paragraph.
  • The button calls setCount to increment the counter by 1 when clicked.

Leave a comment

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