I want to understand how hoisting works with respect to react component. Please check https://codesandbox.io/s/react-hello-world-forked-mzbyn6?file=/src/index.js
I have included Test, Test2 and const hello variables to test hoisting.
According to function hoisting, (reference: Function hoisting), Test function in example could be used before declaration.
But, Test2 is a function expression here, (reference: function expression hoisting), Test2 function should not be used before declaration. It should throw reference error. But, it doesn't throw in react component. why?
Also, hello is a const and should not be used before declaration.(Reference: const hoisting It should also throw an error ideally. Why error is not thrown?
Note: My understanding could be completely wrong. Looking to understand the reasoning here.
Test, Test1 and also hello const are being used from inside App.
App doesn't get executed before their initialization, it just gets declared. By the time App is executed both functions and const are declared and initialized. That's why you don't get an error.
If you want to test the error for the const just put a console.log(hello) above the declaration, but outside of a function that will get called later.
because the App component is just declared before initializing the Test and Test1 components, it is called after initializing them.
I think this example can show you when you should expect a reference error
Here You should expect an error
Uncaught ReferenceError: Cannot access 'test' before initialization
const main = () => {
console.log("TEST", test())
}
// using main() function before initializing the test() function used inside it
main()
const test = () => {
return "TEST Function"
}
but here you will not get any error because use called main() function after declaring test() function
"TEST" "TEST Function"
const main = () => {
console.log("TEST", test())
}
const test = () => {
return "TEST Function"
}
// using the function after initializing the test function used inside
main()
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