Friday, July 15, 2022
HomeWordPress DevelopmentReact cleaner use of setTimeout

React cleaner use of setTimeout


When working with setTimeout we usually do not have to fret about cleansing up our timeouts.

Nonetheless, introducing it into React can create some nasty edge-cases.

This usually occurs as a result of we wish to manipulate knowledge after x time.
The element is perhaps unmounted by then, however the timeout remains to be making an attempt to activate.

You may see some edge circumstances the place your interactions appear to be reverted.
And even get reminiscence leak messages in your console.



Clear your timeouts!

The overall rule of recommendation is to maintain observe of the timeouts you create in your code and clear them.

To wash your timeouts, we will leverage the useEffect cleanup operate.

A fast instance might appear to be this:

export default operate Take a look at() {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const check = window.setTimeout(() => {
      setShow(false);
    }, 1500);
    return () => {
      clearInterval(check);
    };
  }, []);

  return (
    <div>
      <h1>Loading...</h1>
      {present && <p>I'm absolutely loaded now</p>}
    </div>
  );
}
Enter fullscreen mode

Exit fullscreen mode

Nonetheless, I favor to make use of a reference to clear the interval.

const timeoutRef = useRef();

useEffect(() => {
  timeoutRef.present = window.setTimeout(() => {
    setShow(false);
  }, 1500);
  return () => clearInterval(timeoutRef.present);
}, []);
Enter fullscreen mode

Exit fullscreen mode

It will work, however it’s kind of of a trouble to recollect to wash this up on unmount, and so forth.

So why not create a small hook for it?



React useTimeout hook

We will begin by introducing a useTimeout hook.
This hook might be our React model of the setTimeout operate.

This hook ought to have the next choices.

  • Obtain the callback operate (an motion that ought to occur after the timeout)
  • Obtain the delay (time for it to timeout)
  • Return a operate that may be invoked to begin it
import { useCallback, useEffect, useRef, useMemo } from 'react';

export default operate useTimeout(callback, delay) {
  const timeoutRef = useRef();
  const callbackRef = useRef(callback);

  useEffect(() => {
    callbackRef.present = callback;
  }, [callback]);

  useEffect(() => {
    return () => window.clearTimeout(timeoutRef.present);
  }, []);

  const memoizedCallback = useCallback(
    (args) => {
      if (timeoutRef.present) {
        window.clearTimeout(timeoutRef.present);
      }
      timeoutRef.present = window.setTimeout(() => {
        timeoutRef.present = null;
        callbackRef.present?.(args);
      }, delay);
    },
    [delay, timeoutRef, callbackRef]
  );

  return useMemo(() => [memoizedCallback], [memoizedCallback]);
}
Enter fullscreen mode

Exit fullscreen mode

First, we see the parameters handed as callback and delay.
Then we add two references to maintain observe of the lively timeout and lively callback.

Then we’ll want two useEffects, the primary one to take heed to the callback in case it modifications after rendering (this might occur in the event you change any state contained in the callback).

The second is used to deal with the cleanup impact for the timeout. (When the element will get unmounted)

Then we create a useCallback, the place we first filter any current timeouts in our ref.
Then we assign the brand new timeout. This entire callback listens to modifications on all our variables.

And the final half is to return a memoized operate that can take heed to modifications on its callback.

This might sound an overkill technique, however it would assist solidify your timeouts and preserve the whole lot as clear as potential.



Utilizing the hook

To make use of the hook, we will introduce the next code.

import useTimeout from './useTimeout';

const [timeout] = useTimeout(() => {
  setShow(false);
}, 1500);

timeout();
Enter fullscreen mode

Exit fullscreen mode

Wow, manner cleaner, proper?
And now, we solely have one place to maintain observe of our timeouts and guarantee they’re consistently cleaned up.



Thanks for studying, and let’s join!

Thanks for studying my weblog. Be happy to subscribe to my e-mail publication and join on Fb or Twitter



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments