Consider the React code declared inside LoremComponent.tsx below:
const foo = "bar";
export default (props) => {
return (
<h1>{foo}</h1>
)
}
What is the lifetime of variable foo -
I think fundamentally you mistake React for a framework that manages your code for you, in reality, React is merely a library and only provides helper functions to render things to the DOM (or otherwise). React has no say in the lifecycle of variables and memory management, that's handled solely by the JavaScript engine such as V8 or SpiderMonkey.
If the LoremComponent.tsx is not imported anywhere, then this variable wont be declared inside memory? If it is not imported from anywhere it will not be executed. This has nothing to do with React, if it's not imported from anywhere and it's not the app entry point, your bundler (webpack, parcel, rollup etc.) will likely just ignore it and the code will never be executed.
If the component is imported in other component, then what will be the lifetime of the variable foo?
Any JavaScript code in the file will be executed normally including the declaration of the variable foo. This will only happen once. foo will be isolated to its own scope and cannot be accessed by other files unless exported.
Or till the React application is running? React has no say in what happens to variables not managed directly by React (i.e useState). Whether the "React application" is "running" or not cannot affect other aspects of your overall JavaScript application.
Unlike Angular and Vue there's technically no such thing as a "React component file", you can have jsx/tsx files containing one or more React components but technically it's just a normal JavaScript file transpiled with Babel or TypeScript, the file exports functions or classes that the React library can then use.