0

In the below Code of React. head variable is defined below HeadingComponent function. Then why it is not throwing error ?

const HeadingComponent= ()=>{
    return(
       <>
       {head}
        <h1>Hi, This is Heading Component</h1>
        </>
    )
}
const head=<p>This is head</p>```


In the above code we have defined head using "const" which is not hoisted on the top of the scope. So, it should throw an error but Why it is working fine?
  • 2
    Nothing to do with React, everything to do with basic JavaScript. Calling the function will happen *after* the variable definition. – VLAZ Mar 30 '23 at 18:33
  • Also `const` variables *are* hoisted: [Are variables declared with let or const hoisted?](https://stackoverflow.com/q/31219420) – VLAZ Mar 30 '23 at 18:34

1 Answers1

0

Setting a variable outside of the component is the same as setting a global window variable. This is not a bad practice because there are many times that we just need to set variables with static data, ie: an array to be used by the component. Keep in mind that any changes to this variable will not trigger the rerender of the React component (That's why we set dynamic variables using the useState hook).

So the answer for your question is: it does not triggered an error because you set a global variable, therefore, the component has access to the global scope where the variable was set.

Elvio Cavalcante
  • 476
  • 5
  • 10