Understanding how to pass data with props and manage component state
Props and state are both plain JavaScript objects that hold information that influences the output of render. The key difference is that state is managed within the component, while props are passed to the component from its parent.
Props (short for “properties”) are how components communicate with each other. A parent component can pass information to a child component by giving them props.
Props are read-only. A component must never modify its own props:
Copy
Ask AI
// ❌ Never do thisfunction Avatar(props) { props.size = 100; // Error: props is read-only return <img src={props.url} />;}// ✅ Create a new variable insteadfunction Avatar(props) { const size = props.size || 100; return <img src={props.url} width={size} />;}
Pure Functions: React components must act like pure functions with respect to their props. Given the same props, a component should always render the same output.
State updates are batched for performance. Don’t rely on the current state value immediately after calling setState:
Copy
Ask AI
// ❌ This might not work as expectedthis.setState({ count: this.state.count + 1 });this.setState({ count: this.state.count + 1 });// count might only increment by 1// ✅ Use the function form for updates based on previous statethis.setState(prevState => ({ count: prevState.count + 1 }));this.setState(prevState => ({ count: prevState.count + 1 }));// count will increment by 2
According to the React source code in ReactBaseClasses.js, setState accepts:
An object of state variables to update
A function that returns an object of state variables
An optional callback that executes after the state is updated
From React Source: There is no guarantee that this.state will be immediately updated, so accessing this.state after calling setState may return the old value. State updates may be batched together for performance.
If a value doesn’t change over time or doesn’t trigger re-renders, it probably shouldn’t be state. Consider using a regular variable, ref, or derived value instead.