Explain the concept of immutability in React and its importance in component state management.
Instruction: Discuss the principle of immutability in the context of React's state management and why it is considered a good practice.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
Treat props and state as snapshots: do not mutate an object that belongs to a previous render. Create the changed object and every changed ancestor, while sharing unchanged branches. This makes past snapshots reliable and supports reference-based equality checks.
import { useState } from 'react'; export default function Profile() { const [profile, setProfile] = useState({ name: 'Ada', settings: { dark: false } }); function toggle() { setProfile(previous => ({ ...previous, settings: { ...previous.settings, dark: !previous.settings.dark } })); } return <button...