'Hoisting in react components. How does it work?
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Radu Diță |
