ratskin ratskin - 8 months ago 73
React JSX Question

Why are React props immutable?

I've been reading React's Quick Start documentation;

Whether you declare a component as a function or a class, it must never modify its own props

This is a "pure" function, because it doesn't attempt to change its inputs, and always returns the same result for the same inputs:

function sum(a, b) {
return a + b;

This in an "impure" function, because it changes its own input:

function SayHi(props) {
props.name = "Jim"; // TypeError Cannot assign to read only property 'name' of object '#<Object>'
return <h1>Hi {props.name}!</h1>;

Why are React props read-only?

Answer Source

A component should manage its own state, but it should not manage its own props. props is essentially "state that is managed by the component owner." That's why props are immutable.

React docs also recommends to treat state as if it's immutable. That is because by manipulating this.state directly you are circumventing React’s state management, which can be potentially dangerous as calling setState() afterwards may replace the mutation you made.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download