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

101
Vistas
react - function inside useEffect

I've seen some of the example like

  useEffect(() => {
    const getData = () : void => {
      console.log("getData")
    }
    getData()
  }, []);

But I can put the function outside useEffect with the same outcome.

  const getData = () : void => {
      console.log("getData")
  }
  useEffect(() => {
    getData()
  }, []);

What is the difference between these 2?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

One difference is that, if you declare the function outside the effect hook, every time the component re-renders, the function object will be created anew. In contrast, declaring the function inside means that that function only gets created when the hook runs. (The anonymous inline function passed to useEffect still gets created every render, though...) It's really not worth worrying about, but it's a difference.

The main reason some might prefer to declare the function inside the effect hook is to constrain the scope as much as possible - if you do

const fn = () => ...

useEffect(fn, [])

// lots more code

Then, some readers of the code may (very reasonably) worry that // lots more code contains a reference to fn, which can't be determined without reading through all of // lots more code. Constraining your getData to only inside the effect hook makes the intent of the function easier to understand at a glance, especially in a big component.

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