Skip to main content
InterviewHubPRO
Section Overview
Q353

Question 353 of 407

Part 9: React Hooks Deep Dive (262 - 316)

87%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

What is the difference between setState() and replaceState() methods?

junior LevelCode ExampleHooks

When you use setState() the current and previous states are merged. replaceState() throws out the current state, and replaces it with only what you provide. Usually setState() is used unless you really need to remove all previous keys for some reason. You can also set state to false/null in setState() instead of using replaceState().

Code Example

tsx
import React, { Component } from 'react';

class StateMergeDemo extends Component {
  state = { firstName: 'Alex', lastName: 'Morgan', role: 'Architect' };

  updateWithSetState = () => {
    // ✅ setState shallow-merges: lastName and role are preserved
    this.setState({ firstName: 'Taylor' });
    // Resulting state: { firstName: 'Taylor', lastName: 'Morgan', role: 'Architect' }
  };

  updateWithReplaceState = () => {
    // ⚠️ replaceState (legacy, deprecated) completely wipes existing keys:
    // (this as any).replaceState({ firstName: 'Jordan' });
    // Resulting state: { firstName: 'Jordan' } (lastName and role are gone!)
  };

  render() {
    return <div>{this.state.firstName} {this.state.lastName} - {this.state.role}</div>;
  }
}