How to use the useState React hook
Find out what the useState React hook is useful for, and how to work with it!
Check out my React hooks introduction first, if you’re new to them.
One React hook I most often use is useState
.
import React, { useState } from 'react'
Using the useState()
API, you can create a new state variable, and have a way to alter it. useState()
accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state. Since it returns an array we use array destructuring to access each individual item, like this: const [count, setCount] = useState(0)
Here’s a practical example:
import { 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'))
You can add as many useState()
calls you want, to create as many state variables as you want. Just make sure you call it in the top level of a component (not in an if
or in any other block).
Example on Codepen:
See the Pen React Hooks example #1 counter by Flavio Copes (@flaviocopes) on CodePen.
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025