Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!