Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

React Class Component State: How to Initialize, Update, and Reset It

A practical guide to React class state: initialize it, update it safely with setState, understand queued updates, and handle state resets or migration to Hooks.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In a React class component, keep local data in an object on the component instance, read it with this.state, and request changes with this.setState(). Don’t mutate the object directly, and don’t expect a read immediately after setState() to show the new value: React queues the update, and the new state is available on a subsequent render. Class components remain supported, though React recommends function components for new code.

How to initialize and read class state

A class component extends React’s Component and returns its UI from render(). State is an object containing data specific to that component. With modern class-field syntax, initialize it directly on the class:

import { Component } from 'react';

class Counter extends Component {
  state = { age: 42 };

  render() {
    return <p>You are {this.state.age}.</p>;
  }
}

You can also initialize state in a constructor. Call super(props) first, then assign this.state. The constructor is the place for this direct assignment; don’t call setState() there. For current guidance, see React’s Component reference.

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { age: 42 };
  }

  render() {
    return <p>You are {this.state.age}.</p>;
  }
}

How to update state without mutating it

State should be treated as immutable. Don’t assign to this.state after initialization or change a nested object in place; React may not recognize the intended update. Use this.setState() to request a change. An object passed to it is shallowly merged with the existing state, so other top-level fields are preserved.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set a value that does not depend on previous state

this.setState({ name: newName });

Calculate a value from pending state

If the next value depends on the current value, use the updater-function form. React applies it to pending state, avoiding calculations based on an outdated snapshot when updates are queued close together.

this.setState(prevState => ({
  age: prevState.age + 1
}));

Updater functions should be pure: return the next state without performing side effects. React may queue and apply updates during rendering. See React’s setState documentation.

Update a nested object by copying it

Because the merge is shallow, copy each level that changes rather than editing a nested object in place. For example:

this.setState(prevState => ({
  profile: {
    ...prevState.profile,
    name: newName
  }
}));

Why state may look unchanged right after setState

setState() queues an update; it is not a synchronous assignment. Code later in the same event handler still sees the state snapshot from when that handler began. React’s reference puts it this way: “It only affects what this.state will return starting from the next render.”

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If a task must happen after React commits the update, use the optional callback to setState() or handle the change in componentDidUpdate(). In the lifecycle method, compare current props or state with the previous values before scheduling another update; otherwise, an update loop can result. React can batch updates, so don’t rely on an immediate render after each call.

How state persists or resets

React associates state with a component’s identity and position in the rendered UI tree, not merely with a line of source code. State generally persists when the same component remains at the same position. Changing the component type, position, or key can change that identity and reset the state. A key is useful when a new identity should start with fresh local state. React explains this in Preserving and Resetting State and State: A Component’s Memory.

When a prop changes

Avoid copying props into state by default: doing so can leave the component with a stale copy that is difficult to keep synchronized. If a changed prop should reset an entire subtree, consider giving that subtree a key based on the relevant identity. If the value should always reflect the prop, design the component as controlled instead. For a derived value, calculate it during rendering or use memoization when appropriate rather than storing a redundant copy. Use componentDidUpdate() for side effects responding to changed props, comparing current and previous props before acting.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Class state versus Hooks

useState cannot be called inside a class component; Hooks are for function components. React continues to support classes, but recommends functions for new components. When translating state logic, account for behavior as well as syntax:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Concern Class component Function component
State API this.state and this.setState() useState and its setter
Object update behavior An object update shallowly merges into existing state. A setter replaces that state value; explicitly merge when that is the desired behavior.
Calculating from pending state Pass an updater function to setState(). Pass an updater function to the state setter.
Side effects and cleanup Lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount. Hooks such as useEffect, with cleanup where needed.
Recommendation Supported; useful when maintaining existing class-based code. React’s recommended approach for new components.

Lifecycle behavior does not always map one-to-one to a Hook, so migration requires checking when setup, updates, and cleanup occur. The useState reference describes the function-component API.

Keep rendering pure

render() should calculate UI from props, state, and context. Don’t trigger side effects or interact with browser APIs there: React can render more than once or abandon a render attempt. Put side effects in event handlers or lifecycle methods instead. See Components and Hooks must be pure.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.