useState

useState is the React Hook that adds state to a functional component. It returns a pair: the current state value and a function to update it, which triggers a re-render.

React

You call useState with an initial value, and it gives back an array of exactly two items, which you typically destructure: const [count, setCount] = useState(0). The first item is the current value; the second is the setter function.

Calling the setter (like setCount(count + 1)) schedules a re-render with the new value — you should never reassign the state variable directly. State updates can be batched, so when the new value depends on the old one, pass a function: setCount(c => c + 1).

Syntax

const [value, setValue] = useState(initialValue);

Examples

JSX — Renders a button; each click increases the displayed count by one, starting from 0.

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

Learn it in a lesson

See also

Back to the Dictionary