/

Using the useState React Hook

Using the useState React Hook

Learn all about the useState React hook and how to make the most out of it!

If you’re new to React hooks, make sure to check out my React hooks introduction first.

One of the most commonly used React hooks is useState. To start using it, import useState from the ‘react’ package:

1
import React, { useState } from 'react'

With the useState() API, you can create a new state variable and have a way to modify its value. The useState() function accepts the initial value of the state item and returns an array containing the state variable and the function you can call to update the state. Since it returns an array, we use array destructuring to access each item individually. Here’s an example:

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

In this case, the initial value of the state variable “count” is set to 0. The function setCount can be used to update the value of count.

Let’s see a practical example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React, { useState } from 'react'

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

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

ReactDOM.render(<Counter />, document.getElementById('app'))

In this example, we create a state variable count and a function setCount to update its value. The value of count is displayed in a paragraph, and when the button is clicked, the count is incremented by 1.

You can use multiple useState() calls to create as many state variables as you need. Just remember to place the calls at the top level of your component, outside of any conditional statements or blocks.

Check out this example on CodePen:

React Hooks example #1 counter by Flavio Copes

Tags: React, Hooks, useState