Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does React's useEffect hook have access to all function expressions defined beneath it?

I've created a functional component in React like this:

import React, {useEffect} from "react";
import "./styles.css";

export default function App() {

  useEffect(() => logSomething(), [])

  const logSomething = () => console.log('whats up');
  return (<div> hello </div>)
}

This function runs without any errors, and successfully logs out "whats up" in the console.

When I try the following, however, I get a TypeError:

export default function App() {

  useEffect(logSomething(), [])

  const logSomething = () => () => console.log('whats up');
  return (<div> hello </div>)
}

Similarly, I get a TypeError when I try this:

export default function App() {

  useEffect(logSomething, [])

  const logSomething = () => console.log('whats up');
  return (<div> hello </div>)
}

Why does the first example succeed, but the second and third example fail? Is the first function expression getting hoisted somehow? And if so, why aren't the other 2 function expressions being hoisted? Or is this just some quirk with how function references work in JavaScript?

like image 828
Brian K Avatar asked Feb 03 '26 01:02

Brian K


1 Answers

In your second and third examples, you are attempting to use logSomething before it is defined. This results in a type error.

The first example works, because the anonymous function passed into useEffect isn't immediately called, and so it's okay that logSomething isn't defined yet. By the time that function is called, const logSomething has been defined and is in scope.

like image 119
Benjamin Avatar answered Feb 04 '26 14:02

Benjamin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!