Linguine Code

How to use useState in React

Before React 16.8.0, functional components were nothing but just simple markup components without access to React state.

Since the release of React 16.8.0, React functional components may have state!

We can achieve this with one of the new React hooks called, useState().

If you’re not familiar with React state or the new React hooks API, take a look at the links listed below to catch you up to speed!

How to use React useState in functional component

First we’re going to start by importing the useState() function.

Rule of thumb, any React hooks need to be used inside the function component.

In the example above, I’m using useState() and providing a string as the initial value.

On line 5, I’m also destructuring the values that useState() returns, and printing the variable, mssg, inside H1 HTML tags.

What does useState() return?

React useState() always returns an array with 2 values.

The first value in the array is the state value, that you will give or set in the future.

The second value is always a function. This function is the equivalent to the class method, setState().

It’s purpose it to only update the value of that state property.

How to update state with React useState()?

To update the state value with React useState(), we’re going to use the second value provided by the hook function.

In the example below I will be using the useEffect() hook. If you’re not familiar with it check out this article to know how it works: Getting started with React.useEffect().

In this example I’m using React.useEffect() to imitate a componentDidMount() hook.

The logic inside, is to change the value of the state property, mssg, to “BOOM!” in 5 seconds after the component has mounted.

That’s it! Not too difficult to use React useState() in a functional component.

Before we conclude this article let’s take a quick walk to memory lane about the good ol’ fashion usage of React state.

How to initialize state in React class component

To initiate state in the React component, we need to create a property in the class called state.

This property needs to be an object, and you may add all your state data inside that object.

How to update React state in a class component

To update React state in a class component, is pretty simple.

All we need to do is call the setState() method that React provides to us.

This method is still a valid approach, and works well.