Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setTimeout to avoid re-renders in React

There is a pattern that I use often that I feel must be an anti-pattern but I don't know a better alternative.

Occasionally my components may receive one or more events that mean that a re-render is necessary. Sometimes it is the case that I do not know how many times the event handlers will be called. To prevent multiple re-renders as a result of many calls to the handlers I do something like this:

 _myEventHandler() { // may be called multiple times between renders
   if (!this._updateQueued) {
     this._updateQueued = true;
     this._updateTimer = setTimeout(() => {
       this._updateQueued = false;
       this.forceUpdate();
     }, 0);
   }
 }

The problem here is I feel it can't be performant due to the latency between code stopping and the event loop starting.

A real world example of this is when I am using react-visibility-sensor and I have multiple elements change their visibility at once, I don't want to re-render for each element, instead I want just one re-render once all the updates have been received.

Is there another better way to deal with multiple calls?

BTW: if you are going to use the above hack don't forget to call clearTimout(this._updateQueued) in your componentWillUnmount

like image 899
Jack Allan Avatar asked Oct 19 '25 13:10

Jack Allan


1 Answers

You can avoid re-renders using this lifecycle method shouldComponentUpdate (as also mentioned by @fungusanthrax). Keep this inside your react component :

shouldComponentUpdate(nextProps, nextState) {
  return !isEqual(this.props, nextProps) || !isEqual(this.state, nextState);
}

using isEqual from lodash here, make sure to include it. This will only re-render your component when there's a change in props or state value.

To install lodash:

npm install -S lodash

and import isEqual in your component file :

import isEqual from 'lodash/isEqual';
like image 77
Fawaz Avatar answered Oct 22 '25 02:10

Fawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!