Home > Back-end >  react - function inside useEffect
react - function inside useEffect

Time:02-08

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?

CodePudding user response:

The difference between them is the scope of the function.

In the first case if you want to call the getData() function outside the hook it won't work.

And also each time the hook is executed will create the function if it is inside.

CodePudding user response:

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.

  •  Tags:  
  • Related