Issue
I am trying to implement shouldComponentUpdate method in a functional component.
Here is the original method (classfull component)
shouldComponentUpdate(nextProps, nextState) {
return (
this.state.isSelected || nextState.isSelected !== this.state.isSelected
);
}
But, with React memo it seems that I can only access prevProps and nextProps, not nextState.
memo(..., (prevProps, nextProps) => true);
How can I access nextState in a functional component to simulate the shouldComponentUpdate?
Solution
The purpose of react memo is to only check when props changes not state. If you try to do so, you are breaking the rule - the purpose of pure component functionality. What you want is to use the effect hook:
useEffect(()=>{
//...
}, [state that you want to check])
So, with this requirement, avoid using memo as it is not pure component. Component will render when state change, so there's no pure functionality.
While performing shouldComponentUpdate, you don't need to pass dependency array, just check the condition and then you make useEffect as being used as shouldComponentUpdate.
useEffect(()=>{
//check condition here and do logic
})
Answered By - Bhojendra Rauniyar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.