Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 26.4 — Class Components and Legacy Code
React · Example 2 of 5

setState: merging, batching, updaters and PureComponent

name survives every update because setState merges. The object version adds 1 (both calls read the same this.state); the updater version adds 2. PureLabel renders once: its text prop never changed, so the shallow check skips it, while plain Label re-renders with its parent.

Before hooks, components with state were JavaScript classes with this.state, this.setState and lifecycle methods; you need to read them, explain how each maps to hooks, and migrate them safely, and error boundaries still have to be classes.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Convert this class to a function component with hooks: a Toggle with state = { on: false }, a flip = () => this.setState((s) => ({ on: !s.on })) method, and componentDidUpdate that logs on is now true/false when on changes.

02

Write a class Ticker that counts up every second from mount and stops on unmount.

Explain it without notes

01

How does this.setState differ from a useState setter?

02

List the lifecycle methods in order for mount, update and unmount, and say which phase each runs in.

03

How do you migrate a class that subscribes in componentDidMount, re-subscribes in componentDidUpdate and unsubscribes in componentWillUnmount?

04

Why can't error boundaries be written with hooks, and what does each boundary method do?

setState: merging, batching, updaters and PureComponent

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Form render: {"name":"Asha","count":0}
  Label render
  PureLabel render
right after setState, this.state.count = 0
Form render: {"name":"Asha","count":1}
  Label render
Form render: {"name":"Asha","count":3}
  Label render