Middle+
Can props change by themselves? Is there a way to make the component render only when props change?
sobes.tech AI
Answer from AI
Props in React do not change by themselves — they are immutable from the perspective of the component that receives them. Prop changes only occur from above, in the parent component that passes these props.
To make a component re-render only when props change, you can use:
-
React.memo— a wrapper for functional components that memoizes the render result and re-renders the component only if the props have changed based on a shallow comparison. -
For class components —
shouldComponentUpdateorPureComponent, which allow controlling when the component should update.
Example with React.memo:
const MyComponent = React.memo(function MyComponent(props) {
// component will re-render only if props change
return <div>{props.value}</div>;
});
Thus, props do not change by themselves, and the component can be optimized to update only when props change.