Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
useEffect run once hook

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
  }, [])
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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, ...] )
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!