Dzianis Czaplia
Dzianis Czaplia

Reputation: 80

React calls methods in hooks before declaration

I have always been wondering how it works: we can call function expression in useEffect when it was defined below:

const Component = () => {
  useEffect(()=>{func()}, [])
  const func = () => console.log("Why?")
  return <></>
}

Will be glad for explanation or link to resource

Upvotes: 0

Views: 429

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85112

It's nothing specific to useEffect. In javascript in general, it's fine to create a function which references a function on a later line. Only when you call the function does it becomes a problem if you havn't finished initializing the variables.

let a = () => {
  console.log('in a')
  b();
};

let b = () => {
  console.log('in b');
};

a(); // This is fine, both a and b have been initialized

let a = () => {
  console.log('in a')
  b();
};

a(); // ERROR, because b has not been initialized

let b = () => {
  console.log('in b');
};

useEffect won't call your effect function until after the component has finished rendering, so well after func was defined.

Upvotes: 1

Related Questions