🎓 A1Learner
🔍
0 of 50 lessons completed

State and Events

State and events are the pair that makes a page respond. An event runs a handler, and the handler updates the state.

Count up on click

Each click adds 1 to the current count.

function handleClick() {
  setCount(count + 1);
}

Show the count and the button

The paragraph shows the count. The button triggers the change.

<div>
  <p>Count: {count}</p>
  <button onClick={handleClick}>Add 1</button>
</div>

Start the count at 0

The starting value is 0.

const [count, setCount] = useState(0);

Example

import { useState } from 'react';

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

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Add 1</button>
    </div>
  );
}

Key points

  • A click is a common trigger for a state change.
  • The handler calls the setter with the next value.
  • React renders again with the new state.
  • The screen shows the new value after the re-render.
  • The same pattern works for any event.

In this example, App starts count at 0. handleClick calls setCount with count + 1. App returns a paragraph and a button. The paragraph shows Count: 0 at first. A click runs handleClick. React renders again, and the paragraph shows Count: 1.

Note

The handler runs after the event, not during render.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens after a handler calls the setter?