How does React’s shouldComponentUpdate method work?
shouldComponentUpdate is a lifecycle method in class components that determines
whether a component should re-render. By default, a component re-renders when state or
props change, but shouldComponentUpdate allows you to optimize this behavior.
- Return false to prevent a re-render.
- Return true (or omit the method) to allow a re-render.
Example:
class MyComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
// Prevent re-render if props haven't changed
return nextProps.name !== this.props.name;
}
render() {
return <div>{this.props.name}</div>;
}
}