State with useState

View saved

Import and call useState

useState returns the current value and a setter. Calling the setter schedules a re-render.

import { useState } from "react";

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

Initialize once

The argument to useState is the initial value on the first render only.

const [title, setTitle] = useState("Untitled");
const [items, setItems] = useState([]);

Update from previous state

When the next value depends on the old one, prefer the functional form of the setter.

setCount((previous) => previous + 1);

State vs props

  • Props come from outside (parent)
  • State belongs to the component
  • Changing state re-renders that component and its children
  • Do not duplicate props into state unless you truly need a local editable copy

Comments

One comment per signed-in account. Comments are saved with this page’s URL.