Learn the useState Hook in React

Learn the useState Hook in React

What is the useState hook?

The useState hook allows you to add state variables to functional components. Using the useState hook, you can do the following.

  • Declare state variables.
  • Read the value of state variables.
  • Update the value of state variables.

Let's see how you can use the useState hook in React.

Import useState from React

To use useState, the first thing you need is to import the hook from React. The way you do that is by using the syntax below

import React, { useState } from 'react';

Initialize state variable

The next step is to declare an initial state value. The useState hook can take only one argument. But this argument can be of any data type. It can a number, string, boolean, or even an array or object.

To declare an initial state value, you use the following syntax.

import React, { useState } from 'react';

function Example() {

  // Initialize state variable
  const [name, setName] = useState("");
  // ...
}

Let's break down what is happening here.

The code above declares a new state variable name. The useState hook always returns an array with two items. A state variable and a setter function.

  • State variable. The first item in the array is the state variable. The initial value of the state variable will be the initial value passed to useState. In this case, the initial value of name is an empty string "".

  • Setter function. The setter function is what you use to update the state variable. For example, when you want to update the name variable in the example, you will use the setName function.

Use hooks inside functional components

Something you should also keep in mind is that hooks should always be used inside the functional component as in the example above.

Declaring your state variable outside of the functional component will result in an error.

Read value of state variable

So how do you read the value of the state variable?

You can use the state variable directly in your application. By wrapping it with curly braces. For example, if you want to display the name variable, you can use the following code.

import React, { useState } from 'react';

function App() {
  const [name, setName] = useState("Maria");

  return (
    // read the value of name variable
    <p>Name of customer: {name}</p>
  )
}

How to update state

When you want to update state, you use the setter function. Whatever the setter function returns will be the new value of state.

Let's add a button to the App component. When the button is clicked, the customer's name will change from Maria to Tess.

import React, { useState } from 'react';

function App() {
  const [name, setName] = useState("Maria");

  const handleChange = () => {
    // update state
    setName("Tess")
  }

  return (
    <>
      <h2>Name of customer: {name}</h2>
      <button onClick={handleChange}>Change Name</button>
    </>
  )
}

export default App

Play with this code

Updating state with a callback function

When you need to update state, first ask whether the new or updated state is dependent on the previous state value.

For the name example, the value of the previous state was "Maria". The updated value of name is "Tess". The updated state does not depend on the previous state in any way. In that case, you pass the updated value to the setter function directly.

setName("Tess")

Sometimes, the updated state will be dependent on the previous state value.

For example, if the new state is supposed to be the opposite of the previous state. In that case, you first need to get the previous state. And then flip its value to get the opposite.

Assuming there's a state variable with an initial boolean. And you want to flip to the opposite value when a button is clicked. You can use a callback function like so;

import React, { useState } from "react";

function App() {
  const [bool, setBool] = useState(false);

  const handleChange = () => {
    // update state with a callback
    setBool((prevBool) => !prevBool);
  };

  return (
    <>
      <h2>Current Boolean Value: {bool.toString()}</h2>
      <button onClick={handleChange}>Change Boolean</button>
    </>
  );
}

export default App;

Play with this code

Here, instead of updating the state directly, you're doing so with a callback function.

  // update state with a callback
  setBool((prevBool) => !prevBool);

The callback function takes an argument prevBool. You can name it anything you want. But it's common practice to begin the name with "prev" to indicate you're referring to the previous state value. So you'll often see names like prevState, prevValue, prevCount, and others.

Once you have access to the previous state value, you can manipulate it, and return what you want as the updated state value.

In the example above, you had access to the previous state value through prevBool. To get the opposite, return a flipped version of it !prevBool.

Some things to note about useState.

1. Always use the setter function to update state variables.

State variables are immutable. They should always be updated with the setter function and not directly. For example, assuming we have declared a state like this.

const [name, setName] = useState("John")

To update the name from "John" to "Jane", you should use the setName function provided by useState.

  • ❌ name = "Jane"
  • ✅ setName("Jane")

Also, note how the variable is declared with the const keyword. Variables declared with const are constants and cannot be updated.

2. You can use many states in a component.

You can pass arrays and objects as initial state values. But React also allows the declaration of more than one state.

const [friends, setFriends] = useState(["Abby", "Bel", "Cassy"])
const [invitation, setInvitation] = useState(false)
const [balance, setBalance] = useState(1000)

So it's up to you. Depending on your use case, you choose which one works best.

Test your knowledge (useState Challenge)

To test your understanding of the useState hook, I've created a challenge for you.

  • You are to initialize state with a value of zero.
  • Create a function that updates state by adding one.
  • The function should run when a button is clicked.

Your app should look like this.

useState demo.gif

Spend some time working on this challenge. And then you can view the solution below.

Solution to the challenge

Conclusion

This article has been an introduction to the useState hook in React. If you made it this far, you're now familiar with how to use useState in your project. Here's a recap of what you learned.

  • What is useState hook.
  • Initializing state.
  • Reading state variables.
  • Updating state variables.

The next hook you will learn about in this series on react hooks is useEffect.