FRONTENDO
Emberhold Forge
0
0
State Management · Local Component State
New technique

Local state with useState

The smallest ledger is the one on your own workbench. Start here: most state never needs to leave.

A normal variable inside a component is forgotten after every render, and changing it doesn't update the screen. useState gives the component a memory that survives renders, plus a setter that tells React to draw again.

import { useState } from "react";

const Counter = () => {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
};
  • useState(initial) returns [value, setter]. The initial value is only used on the first render.
  • Calling the setter stores the new value and schedules a re-render.
  • Local state belongs to one instance of the component: render <Counter /> twice and each has its own count.