Skip to content
Advertisement

Debouncing / throttling a callback in React using hooks without waiting for the user to stop typing to get the update

I’m using React 16.8.6 with Hooks and Formik 1.5.7 to build a form with a preview of the content that will be generated with that data later on. The form runs fine on its own, but as long as I render the preview as well, everything becomes a bit slow and sluggish.

I’ve fixed that debouncing the onChange of the form using setTimeout, but I’d like it to be called periodically even if the user keeps typing:

JavaScript
JavaScript
JavaScript

Advertisement

Answer

You could define a custom withThrottledCallback hook that takes care of that and replaces/combines these lines:

JavaScript

Into something like this:

JavaScript

And that fires regularly every 500 ms even if the user keeps typing.

This way, rather than using setTimeout directly, you would be able to reuse this functionality declaratively, just like Dan Abramov suggests for setInterval in Making setInterval Declarative with React Hooks.

It will look something like this:

JavaScript
JavaScript
JavaScript

You can also find declarative version of setTimeout and setInterval, useTimeout and useInterval, plus a custom useThrottledCallback hook written in TypeScript in https://www.npmjs.com/package/@swyg/corre.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement