New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› React› State and Events

State and Events

💻 React

Add interactivity with useState and respond to clicks and typing.

Lesson 3 of 9 Tutorial
0 of 9 completed

State is data that changes over time. When state changes, React re-renders the component with the new value.

By the end of this lesson you can:
  • Use useState.
  • Update state from an event.
  • Understand why updates must be immutable.

useState

Call useState with an initial value. It returns the current value and a setter.

import { useState } from "react";

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

  return (
    <button => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

Handling Input

Controlled inputs take their value from state and update it on every change.

function NameForm() {
  const [name, setName] = useState("");

  return (
    <form => event.preventDefault()}>
      <label htmlFor="name">Name</label>
      <input
        id="name"
        value={name} => setName(event.target.value)}
      />
      <p>Hello, {name || "stranger"}</p>
    </form>
  );
}

Updating Objects and Arrays

Never mutate state directly. Create a new object or array so React can detect the change.

const [student, setStudent] = useState({ name: "Ada", score: 0 });

setStudent({ ...student, score: 85 });

const [items, setItems] = useState([]);
setItems([...items, "new item"]);
Tip If the next state depends on the previous value, use the updater form: setCount(current => current + 1).

Practice

  1. Build a counter with increment and reset buttons.
  2. Create a controlled text input that shows a character count.
  3. Add an item to an array in state without mutating it.

Hands-on exercise

Build a component with a button that:
1. Toggles a message on and off.
2. Counts how many times it has been toggled.
3. Shows the message only when it is on.

Recap

State drives the interface. Update it immutably and use the updater form when the next value depends on the old one.

Example

import { useState } from "react";

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

Exercises

Exercise 1. Toggle and count Easy
Build a component with a button that:
1. Toggles a message on and off.
2. Counts how many times it has been toggled.
3. Shows the message only when it is on.
React exercise-1.txt
Expected Output
A working toggle with an accurate count.

Lesson Nav

Lesson sections