Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 20 min

State and events

By the end of this chapter, you'll be able to

  • Declare state with useState and change it
  • React to events: click, typing in a field
  • Update an array or object without modifying it in place
  • Compute derived values instead of storing them

useState

useState is a hook: a special React function, whose name starts with use, called at the start of a component. It returns the current value and a function to change it:

import { useState } from "react";

function Counter() {
  const [views, setViews] = useState(0);
  return (
    <button onClick={() => setViews(views + 1)}>
      Seen {views} times
    </button>
  );
}
  • useState(0): the state starts at 0;
  • views: the current value;
  • setViews(newValue): asks React to change the state and redraw the component.

You never modify views directly (views = views + 1 would redraw nothing): you always go through setViews.

Events

Events are written like attributes in camelCase (onClick, onChange, onSubmit) and receive a function. For an input field, you read the typed value in event.target.value:

function Search() {
  const [text, setText] = useState("");
  return (
    <label>
      Search for a course
      <input value={text} onChange={(event) => setText(event.target.value)} />
    </label>
  );
}

The field displays text, and each keystroke updates the state: it is a controlled field, whose value React always knows.

Only the star changes on screen.

Step 5 of 5
Text description of the animation
  1. The component displays the current state: no favourites.
  2. The student clicks the star of the Python course.
  3. The event handler creates a NEW array and passes it to setFavourites.
  4. React calls the component's function again with the new state.
  5. Only the star changes on screen.

Never modify state in place

React decides to redraw by comparing the old and the new state. For an array or an object, it compares references: is it the same object or another one? If you modify the existing array (with push, splice or an assignment), it is still the same array: React sees no change. So you must always create a modified copy:

const favourites = ["python"];

const added = [...favourites, "sql"];                        // add
const removed = added.filter((slug) => slug !== "python");   // remove
const course = { title: "SQL", views: 3 };
const courseViewed = { ...course, views: course.views + 1 }; // modify an object

console.log(favourites, added, removed);
console.log(course.views, courseViewed.views, course === courseViewed);
["python"] ["python","sql"] ["sql"]
3 4 false

[...favourites, "sql"] creates a new array with all the old elements then the new one; { ...course, views: … } creates a new object replacing one property. The original is never touched.

Compute rather than store

Anything that can be computed from state must not be stored in a second state. For example, the list filtered by the search is computed on every render:

function filter(courses, search) {
  const t = search.trim().toLowerCase();
  return courses.filter((c) => c.title.toLowerCase().includes(t));
}

const courses = [{ title: "Python: your first steps" }, { title: "IP networks" }, { title: "Docker" }];
console.log(filter(courses, "  PY ").map((c) => c.title));
console.log(filter(courses, "").length);
["Python: your first steps"]
3

In the component: const visible = filter(courses, search);. A single state (search), and the visible list is always consistent with it.

Mini-lab: updates without in-place modificationJavaScript

Output

Click “Run” to execute your code.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: toggling a favourite

Write a pure function toggle(favourites, slug) that adds slug to the list if it is not there, and removes it if it is, without modifying the list received. Then show how to use it in a component with useState.

Hint 1
favourites.includes(slug) tells whether the course is already a favourite.
Hint 2
To remove: filter; to add: [...favourites, slug].
Show the solution and common mistakes
function toggle(favourites, slug) {
  return favourites.includes(slug) ? favourites.filter((s) => s !== slug) : [...favourites, slug];
}

const start = ["python"];
const a = toggle(start, "sql");
const b = toggle(a, "python");
console.log(start, a, b);
["python"] ["python","sql"] ["sql"]
function FavouriteButton({ slug, favourites, setFavourites }) {
  const active = favourites.includes(slug);
  return (
    <button aria-pressed={active} onClick={() => setFavourites(toggle(favourites, slug))}>
      {active ? "★ Favourite" : "☆ Add to favourites"}
    </button>
  );
}

aria-pressed tells screen readers that the button is a toggle, and which state it is in.

Common mistakes:

  • Writing onClick={setFavourites(toggle(favourites, slug))} without () =>: the function is called during rendering, on every render, which causes an infinite loop.
  • Using favourites.push(slug) in toggle: the starting list is modified, and React does not redraw.

Summary

  1. 1useState returns the current value and a function that changes it and redraws the component.
  2. 2Events (onClick, onChange…) receive a function; a controlled field reads event.target.value.
  3. 3State is never modified in place: copies are made with [...t], filter, map or { ...o }.
  4. 4React compares references: an array modified with push is not seen as a change.
  5. 5What can be computed from state, such as a filtered list, is computed on every render instead of being stored.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.