InterviewHubPRO
Section Overview
Q390

Question 390 of 445

Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

88%
React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

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

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>;
  }
}