Module 33: State and Events

Lesson 1 of 5 · 15–25 minutes

State with useState

🏠The everyday picture

A scoreboard at a cricket match. When the score changes, the board is updated, and everyone watching sees the new score. State is the scoreboard; React redraws the screen whenever it changes.

📘What it really is

import { useState } from "react";

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

🖱️Try it

Add a "Show closed enquiries" button to the dashboard. Store showClosed in state (starting false), toggle it on click with setShowClosed(!showClosed), and only show the closed panel when it's true. Change the button text to match ("Show"/"Hide").

✅Quick check

You change a normal variable in a click handler, but the screen doesn't update. Why?

Show the answer

Only state changes (through the setter) cause React to re-render.

What does useState(0) return?

Show the answer

A pair: the current value, and a function to change it.

← BackModule 33
ProLearners Assist