I can invoke a link by history.push("/path")
. To access history
, I have to use withRouter
which passes multiple props to the component. match
passed by withRouter
is different even if the path does not change. This causes PureComponent
to rerender. Is there a way to work around this?
Example:
class HomeButton extends PureComponent {
onClick = () => {
const { history } = this.props;
history.push("/");
}
render() {
return <Button onClick={this.onClick}/>
}
}
export default withRouter(HomeButton);
I used shallowEqualExplain to check which props causing the update.
Memoization using useMemo() and UseCallback() Hooks Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.
memo() If you're using a React class component you can use the shouldComponentUpdate method or a React. PureComponent class extension to prevent a component from re-rendering.
React shouldComponentUpdate is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed. Only use this method if when a component will stay static or pure. The React shouldComponentUpdate method requires you to return a boolean value.
A second or subsequent render to update the state is called as re-rendering. React components automatically re-render whenever there is a change in their state or props.
I'd suggest to use Component
instead of PureComponent
if you don't want to update Button
.
React.PureComponent’s shouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences.
Ref: https://reactjs.org/docs/react-api.html#reactpurecomponent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With