Optimizing reactivity with shouldUpdate
Show how to use the 'shouldUpdate' option to optimize reactivity and prevent unnecessary component updates.
<div id="app"></div>
This is the HTML structure where our component will be mounted.
/* Add to your CSS file or inside a <style> tag */
#app { padding: 20px; font-family: Arial, sans-serif; }
Basic CSS to style the application's div container.
/* JavaScript code using a library like Preact or similar */
import { h, render, Component } from 'preact';
class MyComponent extends Component {
shouldComponentUpdate(nextProps, nextState) {
// Only update if the color prop has changed
return nextProps.color !== this.props.color;
}
render({ color }) {
return <div style={{ color: color }}>Text Color: {color}</div>;
}
}
// Initial props for our component
const props = { color: 'blue' };
render(<MyComponent {...props} />, document.getElementById('app'));
// After 2 seconds, try to update with the same color
setTimeout(() => {
render(<MyComponent {...props} />, document.getElementById('app'));
}, 2000);
// After 4 seconds, update with a different color
setTimeout(() => {
const newProps = { ...props, color: 'red' };
render(<MyComponent {...newProps} />, document.getElementById('app'));
}, 4000);
In this JavaScript code using a library like Preact, the 'shouldComponentUpdate' method is used in the 'MyComponent' class to determine if the component should update or not. The comparison between nextProps and current props is done to check for relevant changes. The component only updates when the 'color' prop changes, preventing unnecessary re-renderings. Two timeouts are used to demonstrate updates: the first timeout will not cause a re-render because the color prop remains the same; the second timeout will cause a re-render because the color changes to red.