The Error When You Try to Mutate Props
What you'll learn: What happens when you try to change props directly and why React stops you.
The Immutability Error
Remember how we learned that props are read-only? React doesn't just suggest you don't mutate props—it actively prevents you from doing so in certain environments.
When you try to reassign or mutate props, you'll encounter errors depending on your setup:
In strict mode (which most modern React apps use), attempting to mutate props triggers a runtime error:
function Greeting(props) {
props.name = "Changed!"; // ❌ Error: Cannot assign to read only property
return <h1>Hello, {props.name}</h1>;
}
With TypeScript, you'll get a compile-time error before your code even runs:
function Greeting(props: { name: string }) {
props.name = "Changed!"; // ❌ TypeScript Error: Cannot assign to 'name'
// because it is a read-only property
return <h1>Hello, {props.name}</h1>;
}
Why This Protection Exists
These errors are helpful guardrails. They catch bugs before they cause confusing behavior in your app. If React allowed prop mutations, you'd break the one-way data flow rule, making your app unpredictable.
Think of it like a locked display case in a museum: you can look at the artifact (read the prop), but you can't reach in and change it (mutate the prop). The lock isn't there to annoy you—it's protecting the integrity of the exhibit.
What to Do Instead
If you need to work with a different value, create a new variable:
function Greeting(props) {
const modifiedName = props.name.toUpperCase(); // ✅ Create new value
return <h1>Hello, {modifiedName}</h1>;
}
Key Takeaway: Modern React environments actively prevent prop mutations with runtime or compile-time errors, enforcing the read-only nature of props and protecting your app's data flow.