Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda