How to use the React useState Hook
© https://reactjs.org/

How to use the React useState Hook

The useState Hook makes function components stateful

By Mario Kandut

Hooks are available in React, since v16.8 (2018) and enable function components to manage state and side effects.

They work side-by-side with existing code. and have a lot of other great features, check out the Intro to React Hooks blog post.

💰 Start your cloud journey with $100 in free credits with DigitalOcean.

React provides a few built-in Hooks like useState. This blog post is about the useState hook.

useState

Let's start with a basic counter as an example. We start from a class component and refactor it to a function component.

Class

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button
          onClick={() =>
            this.setState({ count: this.state.count + 1 })
          }
        >
          Click me
        </button>
      </div>
    );
  }
}

The state starts as { count: 0 }, and we increment state.count when the user clicks a button by calling this.setState().

Function Components

A friendly reminder, function components look like this:

const Example = props => {
  // You can use Hooks here!
  return <div />;
};

or like this:

function Example(props) {
  // You can use Hooks here!
  return <div />;
}

Before Hooks these components were often referred to as stateless components, with the introduction of Hooks this has changed.

What is a Hook and when would I use it?

A Hook is a function that lets you “hook into” React features. The useState hook lets you add React state to function components.

import React, { useState } from 'react';

function Example() {
  // ...
}

If a function component needs some state, previously (before 2018) you had to convert it to a class component, now you can use a Hook inside the existing function component.

Declaring State

In the class component we initialized state in the constructor by setting this.state to { count: 0 }.

this.state = {
  count: 0,
};

In a function component, we have no this, it's just a function not a class, so we can't use this.setState(). We call the useState Hook directly inside our component:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
  // ...

When you call useState you declare a state variable. In the example above the variable is called count, but it can be anything. Normally, variables “disappear” when the function exits, but state variables are preserved by React.

The argument passed to useState is the initial state. The state doesn't have to be an object.

useState returns a pair of values - the current state and, a function that updates it.

In the example above:

  • We declare a state variable called count
  • Set the initial value of count to 0. React will remember its current value between re-renders, and provide the most recent one.
  • If we want to update the current count, we can call setCount.

Reading State

To display the current count in a class, we read this.state.count:

<p>You clicked {this.state.count} times</p>

In a function, we can use count directly:

<p>You clicked {count} times</p>

Updating State

In a class, we have to call this.setState() to update the count state:

<button
  onClick={() => this.setState({ count: this.state.count + 1 })}
>
  Click me
</button>

In a function, we already have setCount and count as variables so we don’t need this:

<button onClick={() => setCount(count + 1)}>Click me</button>

Class to Function Component - Counter

The entire function component looks like this:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

What Do Square Brackets Mean?

The square brackets when we declare a state variable with useState are JavaScript array destructuring.

So this syntax:

const [fruit, setFruit] = useState('banana');

Is destructured to this:

let fruitStateVariable = useState('banana'); // Returns a pair
let fruit = fruitStateVariable[0]; // First item in a pair
let setFruit = fruitStateVariable[1]; // Second item in a pair

When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it.

TL;DR

  • The useState Hook enables function components to be stateful.
  • useState removes complexity and can be used side-by-side with existing code. No need for a big refactor.

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.

If you want to know more about React, have a look at these React Tutorials.

References (and Big thanks):

React Hooks Intro, ReactJS

Scroll to top ↑

We use cookies 🍪 to build a better website.! Close to accept or learn more.