Before we talk about the useState hook, let’s remember what “state” means. In a simple way, state is your component’s data storage, giving it the power to memorize the value of a variable, saves the new value in case it is changed according to user interaction. Therefore, useState is a Hook that lets you add React state to function components.

To use the hook, just import it from React:

import React, { useState } from "react";

Now let’s imagine a hypothetical situation, we have a page on a website where the user must to read some information and agree to continue browsing.

For this we can create a component called “AgreePage”, where this component will have a state that controls whether or not the user accepts the terms

import React, { useState } from "react"

export default function AgreePage() {
  const [agree, setAgree] = useState(false);
};

Let’s expand a bit on the above code piece:

  • agree: The variable name, we can display it to the user like so {agree}.
  • setAgree: The setter function as we can’t modify the agree variable directly.
  • useState(false): The initial constructor, in this case, we set it to false

It doesn’t matter what names you use. But it can be handy to think of the pattern as:

[<getter>, <setter>] = useState(<initialValue>)

Now let’s build the whole component

import React, { useState } from "react"


export default function AgreePage() {
  const [agree, setAgree] = useState(false);


  return (
    <div className="agreePage">
      <p>Some information here...</p>

      <button onClick={() => setAgree(true)}>I Agree</button>

      <button
        onClick={() => {
          // navigate to another page...
        }}
        disabled={!agree}
      >
        Continue...
      </button>
    </div>
  );
};

We have a paragraph with the information, a button he can click to “agree” and a second button that will remain blocked until he agrees.

So, when the user clicks on the “I Agree” button, the setAgree function will make the value of the “agree” status true and, consequently, the button below will no longer be disabled, allowing him to navigate

Very simple, right?

Let’s see if you understand, what will the code below do?

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


  const add = () => {
    setCount(count + 1);
  };


  return (
    <div className='Counter'>
      <p>You clicked {count} times</p>
      <button onClick={add}>Click me</button>
    </div>
  );
}

This time, we create a state called count and we have the setCount function that will change its value. Continuing we have a button that when clicked calls the “add” function. The function takes the current value of “count” and adding the value 1

Now what would happen if we do that?

const add = () => {
    setCount(count + 1);
    setCount(count + 1);
};

We add one more line that adds the value to “count”, so at each click we will have: 2,4,6,8…

Right?

Wrong!!

In this case, as React will get the initial value and it has not been changed yet, it uses this value in the second call as well as in the first one, that is, both will be “0 + 1” for example

We can fix this by making the following change

const add = () => {
    setCount((prev) => prev + 1);
    setCount((prev) => prev + 1);
};

That’s right!!

Thank you for reading, I hope you had some fun learning about useState in React.

You can also consult the documentation on the official React website by clicking here

Leave a comment

Trending

Design a site like this with WordPress.com
Get started