React Hooks - How do I implement shouldComponentUpdate?
In addition to Avinash's answer. Important note for returning values:
shouldComponentUpdate() {
// returns true by default
// return false if you don't need re-render
}
export default React.memo(Component, (props, nextProps) => {
if(props.prop1 === nextProps.prop1) {
// return true if you don't need re-render
}
})
In a comment above Gabriele Petrioli links to the React.memo documentation that explains how to implement shouldComponentUpdate. I was googling combinations of shouldComponentUpdate + useEffect + "react hooks", and this came up as the result. So after solving my problem with the linked documentation I thought I would bring the information here as well.
This is the old way of implementing shouldComponentUpdate:
class MyComponent extends React.Component{
shouldComponentUpdate(nextProps){
return nextProps.value !== this.props.value;
}
render(){
return (
<div>{"My Component " + this.props.value}</div>
);
}
}
The New React Hooks way:
React.memo(function MyComponent (props) {
return <div>{ "My Component " + props.value }</div>;
})
I know you were probably asking for more in your question, but for anyone coming from Google looking for how to implement shouldComponentUpdate using React Hooks, there you go.
The documentation is here: how-do-i-implement-shouldcomponentupdate
Adding to PAT-O-MATION's answer,
React.memo also accepts a second parameter, which is function which can be used to determine if a component
should render or not.
if the function returns true then component won't re-render on change of that prop, conversely it updates when the return value is false
function SomeComp({prop1, prop2}) {
return(
..
)
}
React.memo(SomeComp, (props, nextProps)=> {
if(props.prop1 === nextProps.prop1) {
// don't re-render/update
return true
}
})
Note: Component would only re-render when the callback function returns false, so in the above case even if the prop2 value changes it won't re-render
An alternative might be to use useRef to hold your data, and use useState ONLY to store the data you want to display. Sometimes this works better than the memo approach: I've had a case recently where React was still rendering needlessly when using React.memo, and it was messing up some PIXI display. The approach below fixed it for me... hopefully I did not do an anti-pattern :-)
const countRef = useRef(0);
const [countDisplay, setCountDisplay] = useState(0);
yourUpdateFunction = () => {
// This is where count gets updated
countRef.current = countRef.current + 1;
if ((countRef.current % 2) === 0) setCountDisplay(countRef.current);
}
return (<p>countDisplay</p>);