State and events

Respond to a click and change what is on screen.

Your React code is compiled and run by React itself, inside your browser tab. Nothing to install.

Responding to a click

onClick on a button is given a function to run when the button is clicked.

A click on its own changes nothing you can see. For that, the component needs to remember something.

Example
export default function App() {
  return (
    <button onClick={() => console.log("Clicked")}>Say hello</button>
  );
}

Remembering with state

useState gives a component a value it remembers between clicks, and a function to change it. useState(0) starts the value at 0.

When that function is called with a new value, React draws the component again with it. You never change the page yourself: you change the state and the page follows.

Example
import { useState } from "react";

export default function App() {
  const [cups, setCups] = useState(0);
  return (
    <div>
      <p>Cups ordered: {cups}</p>
      <button onClick={() => setCups(cups + 1)}>One more</button>
    </div>
  );
}

Your turn: a counter

State, a paragraph and a button together.

Practice task

Show a paragraph reading Count: 0 and a button that says Add. Each click of the button must add one to the count.

Your answer is run and checked in the lesson. Create a free account to try it.

Showing something only sometimes

State can decide whether an element is shown at all.

{open && <p>…</p>} shows the paragraph only while open is true. condition ? a : b chooses between two things.

Example
import { useState } from "react";

export default function App() {
  const [open, setOpen] = useState(false);
  return (
    <div>
      <button onClick={() => setOpen(!open)}>{open ? "Hide hours" : "Show hours"}</button>
      {open && <p>7 am to 2 pm, every day</p>}
    </div>
  );
}

Your turn: on and off

One button, two states.

Practice task

Show a paragraph that reads Light is off and a button that says Switch. Each click must flip the paragraph between Light is off and Light is on.

Your answer is run and checked in the lesson. Create a free account to try it.