xfscrypt
xfscrypt

Reputation: 276

React: How to frequently update a state

I am trying to display a width of an svg rectangle (using the svgdot.js library). I have a listener on the rectangle resize:

   rect.on('resizing', function (event: any) {
      self.setState({width: rect.width(), height: rect.height()});
    });

However, this triggers, ofcourse, a state update verry frequently. Though I have a verry simple UI, the page becomes verry laggy.

Is there a more efficient way where I can realtime update the state or a variable without the UI becoming slow?

Upvotes: 0

Views: 226

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

You should use debouncing or throttling.

Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in “execute this function only if 100 milliseconds have passed without it being called.”

Throttling enforces a maximum number of times a function can be called over time. As in “execute this function at most once every 100 milliseconds.”

import debounce from 'lodash.debounce';

rect.on(
  "resizing",
  debounce(function (event: any) {
    this.setState({ width: rect.width(), height: rect.height() });
  }, 1000)
);

Upvotes: 3

Related Questions