ReactEasy

What is setState()?

setState is the class component method for updating state: this.setState(partialState) or this.setState((prevState, props) => partialState). It shallow-merges the update into this.state and schedules a re-render. In function components, the equivalent is the setter returned by useState, which replaces the value instead of merging.

Class component setState

  • Merges at the top level: this.setState({ name }) keeps other keys.
  • Updater form: this.setState((prev) => ({ count: prev.count + 1 })) when depending on previous state.
  • Callback: this.setState(update, () => { /* runs after re-render */ }).
  • Batched: multiple calls are combined into one render (in all contexts since React 18).
  • Never assign this.state = ... outside the constructor; React will not re-render.

Function component setters (useState)

  • Replace the value: setUser({ ...user, name }) is needed to keep other fields.
  • Same updater form: setCount((c) => c + 1).
  • No callback argument; use useEffect or compute the value up front.
  • Bail out if the new value is identical (Object.is).

Interview point

Explain the merge vs replace difference and that both are batched and not applied immediately.

Code example

tsx
1import { Component, useState } from "react";
2
3// Class component: setState merges
4export class ProfileClass extends Component<{}, { name: string; age: number }> {
5 state = { name: "Ada", age: 36 };
6
7 birthday = () => {
8 this.setState(
9 (prev) => ({ age: prev.age + 1 }), // name is preserved by merging
10 () => console.log("after update:", this.state.age)
11 );
12 };
13
14 render() {
15 return <button onClick={this.birthday}>{this.state.name} is {this.state.age}</button>;
16 }
17}
18
19// Function component: the setter replaces, so spread to keep fields
20export function ProfileFn() {
21 const [profile, setProfile] = useState({ name: "Ada", age: 36 });
22 const birthday = () => setProfile((p) => ({ ...p, age: p.age + 1 }));
23 return <button onClick={birthday}>{profile.name} is {profile.age}</button>;
24}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app