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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With