Home > Blockchain >  useEffect run once hook
useEffect run once hook

Time:10-19

I found this lib https://react-hooks.org/docs/useeffectoncewhen but I'm confused. Why does it even existed and in what purpose it's used? Isn't I can achieve the same thing using useEffect?

useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 3000); // Countdown for 3 sec
  }, [])

CodePudding user response:

You can do the same thing with useEffect:

"If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument"

Docs

You can also supply a list of dependencies that trigger the effect running again if they change.

useEffect( () => { doSomething() } , [ifThisChangesRunFuncAgain, orThis, ...] )

CodePudding user response:

The hook is useEffectOnceWhen, not just useEffectOnce. Per the source you linked:

Runs a callback effect atmost one time when a condition becomes true

Here's the source code of that hook:

/**
 * useEffectOnceWhen hook
 *
 * It fires a callback once when a condition is true or become true.
 * Fires the callback at most one time.
 *
 * @param callback The callback to fire
 * @param when The condition which needs to be true
 */
function useEffectOnceWhen(callback: () => void, when: boolean = true): void {
  const hasRunOnceRef = useRef(false);
  const callbackRef = useRef(callback);
  useEffect(() => {
    callbackRef.current = callback;
  });
  useEffect(() => {
    if (when && !hasRunOnceRef.current) {
      callbackRef.current();
      hasRunOnceRef.current = true;
    }
  }, [when]);
}

As you can see, it does something more advanced than just being called once at the beginning of the hook: it gets called once the condition passed in becomes true for the first time.

  • Related