简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM