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
useEffector 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";23// Class component: setState merges4export class ProfileClass extends Component<{}, { name: string; age: number }> {5 state = { name: "Ada", age: 36 };67 birthday = () => {8 this.setState(9 (prev) => ({ age: prev.age + 1 }), // name is preserved by merging10 () => console.log("after update:", this.state.age)11 );12 };1314 render() {15 return <button onClick={this.birthday}>{this.state.name} is {this.state.age}</button>;16 }17}1819// Function component: the setter replaces, so spread to keep fields20export 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.