Performance: Props as read-only data
This concept affects how React components update and render, impacting interaction responsiveness and rendering speed.
function Child({ data }) { const newValue = 10; // Use local state or variables instead return <div>{newValue}</div>; } function Parent() { const info = { value: 5 }; return <Child data={info} />; }
function Child({ data }) { data.value = 10; // Mutating props directly return <div>{data.value}</div>; } function Parent() { const info = { value: 5 }; return <Child data={info} />; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Mutating props inside child | Causes extra DOM updates | Multiple reflows if state changes triggered | Higher paint cost due to unnecessary updates | [X] Bad |
| Treating props as read-only | Minimal DOM updates | Single reflow when needed | Lower paint cost with optimized rendering | [OK] Good |
props are read-only?props inside the child component. -> Option Atitle inside a functional component?props.props.title. Using this.props is for class components.function Greeting(props) {
props.name = "Alice";
return <h1>Hello, {props.name}!</h1>;
}
// Usage: <Greeting name="Bob" />props.name = "Alice" mutates the value before the return, so the output is "Hello, Alice!".function Counter(props) {
props.count = props.count + 1;
return <div>Count: {props.count}</div>;
}props.count = props.count + 1; tries to change props directly, which is not allowed.props are read-only?Pass the test and this pattern moves unknown