Shallow Immutability: Objects and Arrays
What you'll learn: Props references can't be changed, but nested properties inside objects and arrays can be mutated—and why you must avoid this.
The Core Idea
React prevents you from reassigning props entirely (props = somethingElse throws an error), but it can't stop you from mutating the contents of objects or arrays passed as props. This is called shallow immutability—the reference is protected, but the nested data isn't.
function UserCard({ user }) {
// ❌ React prevents this:
// user = { name: "Different Person" }; // Error!
// ⚠️ But React CAN'T prevent this:
user.name = "Changed Name"; // This WORKS but is wrong!
return <h2>{user.name}</h2>;
}
Why This Matters
Even though React can't stop you from mutating nested properties, you absolutely must not do it. Why?
-
Props flow downward from parent components. When you mutate
user.name, you're changing data that belongs to the parent, breaking the one-way data flow. -
Other components may reference the same object. Your mutation affects them too, creating unpredictable bugs.
-
React's change detection can fail. React compares references to detect changes. If you mutate properties without changing the reference, React might not re-render when it should.
The Analogy
Think of props like a borrowed book. React prevents you from swapping it for a different book (immutable reference), but it can't physically stop you from writing in the margins (mutating contents). Just because you can doesn't mean you should—it's not your book to modify.
Key Takeaway: Props references are immutable, but React can't enforce immutability of nested object/array properties—you must manually avoid mutating them to preserve predictable data flow.