Sikau

React · Day 8 · about 30 min

State with useState

Components that remember.

Why doesn't it update?

Try changing an ordinary variable when a button is clicked — the screen won't change. React only re-renders when state changes. State is a component's memory, and useState is the first hook you'll learn.

useState

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You ordered {count} plates of momo</p>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={() => setCount(0)} disabled={count === 0}>Reset</button>
    </div>
  );
}
  • Hooks are called at the top level of a component — never inside if statements or loops.
  • Each component instance has its own state: two <Counter />s count separately.
  • Updating from the previous value? Use the function form: setCount((c) => c + 1) — it's always correct, even with several updates in a row.

The rest of this lesson

  • What a re-render isexplain
  • What belongs in stateexplain
  • Three updates?predict
  • Three updatespredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React