Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent withRouter causing rerendering PureComponent?

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.

like image 763
Joshua Avatar asked Aug 02 '18 08:08

Joshua


People also ask

How can you prevent re-rendering a total component if it hasn't changed?

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.

How do you prevent a child component from rendering?

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.

How do I stop re-rendering lists in react?

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.

What is re-rendering in react JS?

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.


Video Answer


1 Answers

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

like image 133
hsz Avatar answered Sep 21 '22 11:09

hsz