State with the useState Hook

Site Admin · 11 Sep 2026 · 9 views

State with the useState Hook

State is data that changes over time and triggers re-renders. In function components you manage it with the useState hook.

The basic pattern

import { useState } from 'react';

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

useState returns a pair: the current value and a function to update it. The argument passed in, here 0, is the initial value. When setCount runs, React re-renders the component with the new value.

Why not just mutate a variable

Plain variables do not notify React that something changed. Calling setState tells React to schedule a re-render. Always update state through the setter, never by assigning directly over the state variable.

Different state types

State can hold any value: numbers, strings, booleans, arrays, objects. A common example:

const [user, setUser] = useState({ name: '', loggedIn: false });

Functional updates

When the new value depends on the previous one, pass a function to the setter. This avoids stale values when updates happen quickly:

const [count, setCount] = useState(0);
setCount((prev) => prev + 1);

Keep state minimal

Store the smallest amount of data needed and compute everything else during rendering. If two values always change together, keep them in one object instead of two separate states.

Key Points

  • useState returns the value and its setter.
  • Calling the setter triggers a re-render.
  • Never mutate state directly.
  • Use functional updates when the new value depends on the old one.
  • Keep stored state minimal.
Share this post:

Comments (0)

Please login or register to comment.