Facebook Pixel
Step-by-Step Guide

How to Use the useState Hook in React

A step-by-step guide on how to add and manage local state inside a functional component using the useState hook.

Understand What State Is

State is data that belongs to a component and can change over time. When state changes, React automatically re-renders the component to reflect the new data on screen. Regular JavaScript variables do not trigger re-renders when changed, which is why you need useState.

Import useState

At the top of your component file, import useState from the react package. Write: import { useState } from 'react'. This gives you access to the hook inside your functional component.

Call useState with an Initial Value

Inside your component function, call useState and pass the initial value of your state as an argument. This can be a number, string, boolean, array, object, or null. useState returns an array with exactly two elements.

Destructure the Returned Array

Destructure the return value of useState into two variables. The first variable holds the current state value. The second variable is the setter function you call to update the state. A common pattern is: const [count, setCount] = useState(0).

Read the State Value

Use the first variable anywhere in your component just like a regular JavaScript variable. Reference it inside JSX with curly braces to display it on screen. Every time the state updates, React re-runs the component function and the variable holds the latest value.

Update State Using the Setter Function

Never modify the state variable directly. Always call the setter function with the new value. For example, call setCount(5) to set the count to 5. React schedules a re-render and the component function runs again with the updated value.

Update State Based on Previous Value

When the new state depends on the old state, pass a callback function to the setter instead of a direct value. Write setCount(prevCount => prevCount + 1). React guarantees that prevCount is always the most recent state value, which is critical when multiple updates happen in quick succession.

Use Multiple useState Calls

You can call useState multiple times in the same component, once for each independent piece of state. Each call manages its own separate value. Keep state variables focused on one concern each rather than cramming everything into one large object.

Ready to master this completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.