Bitpath

Lesson 1 · Unit 02

State

useState, renders as snapshots, updater functions and batching.

13 exercisesabout 3 min

What you practise

  • useState, a render is a snapshot, why the value does not change until the next render, updater functions, batching

Try a question from this lesson

Pick one

A first try at a counter, with a plain variable. The user clicks three times. What does the button show?

TypeScript
function Counter() {
  let count = 0;
  const add = () => { count += 1; };
  return (
    <button onClick={add}>{count}</button>
  );
}

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

State

useState gives a component memory. It returns a pair: the current value, and a function that sets a new one. Calling the setter does two things: React stores the new value, and it schedules another call of your component, which reads that value. The argument is the initial value, used on the first render only.

TypeScript
import { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  const add = () => setCount(count + 1);
  return (
    <button onClick={add}>{count}</button>
  );
}

Concept

A render is a snapshot

Each render gets its own count, fixed for that render: the JSX, the handlers and everything else created in that call see the same value. A setter does not change the variable you already have. It asks React for a new render, and that render gets a new constant with the new value.

TypeScript
function onClick() {
  // in this render, count is 0
  setCount(count + 1); // queues 0 + 1
  setCount(count + 1); // queues 0 + 1
  console.log(count);  // still 0
}

10 more exercises in the app

  • 3× type the answer
  • 4× multiple choice
  • 1× order the lines
  • 1× true or false
  • 1× fill the blanks

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy