Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda