The useState Hook
Components often need to change what is on the screen as a result of an interaction. Typing into a form should update the input field, clicking a button should open a menu.
To remember data between renders, components use state. The most common Hook for adding state to a component is useState.
Basic Usage
To use it, import it from React. The hook returns an array with exactly two items:
- The current state value.
- A required function that lets you update the state.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
You pressed me {count} times
</button>
);
}
How State Triggers Renders
When you call setCount(count + 1), two things happen:
- React stores the new state internally.
- React queues a re-render of the component.
During the next render, useState returns the new, updated value, and React updates the DOM to reflect the new count.
State is Isolated
State is fully local to a specific instance of a component on the screen. If you render the <Counter /> component twice, they will each have a completely independent count. Modifying one counter does not affect the other.