Say I have a React component that looks like this:
const MyReactComponent = (props) => {
const my_function = () => {// do some stuff...}
return (
<div>
<p>
Hello {props.name}, would you like to eat a {my_function()}?
</p>
</div>
)
}
Would the code defining my_function
be re-evaluated every time My_React_Component is used? (By "used", I mean "appears in the JSX.")
Yes. Sort of. Maybe no.
When executing a javascript function each line in the function will get executed/evaluated. So the function definition will be evaluated again each time your function is called. Since you are using a function component then yes, the function will get redefined not only each time your component is used but also each time it is re-rendered.
However, does it mean that javascript recompiles the function each time it is defined? Maybe. In theory javascript does not need to recompile the function. It only needs to create a new closure. In theory you do not need to recompile a function to create a new closure - you just need a copy of the function's stack frame. Due to heavy competition from Netscape4 onwards most javascript interpreters have been optimised to such an extent that almost no modern javascript interpreter will recompile the inner function again. So the slowest part of function definition happens only once.
Still, in theory this still gives class-based components a small advantage over function components: the function definition does not need to be evaluated again on each render. In practice the performance difference is very small.
If you really insist on avoiding reevaluating the function definition you can always declare it outside of the component. This will surely evaluate the function only once. However you cannot use closures to share variables with the function but this is not much of an issue as you can always pass the variables into the function. Declaring functions outside of components also encourage you to write pure functions because of the inability to share closures:
const my_function = (propsArgs) => {// do some stuff...}
const MyReactComponent = (props) => {
return (
<div>
<p>
Hello {props.name}, would you like to eat a {my_function(props)}?
</p>
</div>
)
}