'What does it change to declare a constant above or bellow a React functional component?
My question is what does it change to declare a constant above or bellow a React functional component (or a class component also) ? for example what is the difference if I do :
const myName = "Olivier";
const myReactComponent = () => {
const whatsMyName = (name) => console.log(name);
whatsMyName(myName);
return(<div></div>);
}
OR
const myReactComponent = () => {
const myName = "Olivier";
const whatsMyName = (name) => console.log(name);
whatsMyName(myName);
return(<div></div>);
}
If someone could explain to me the difference It would be great ! Also for example Could I move the whatsMyName function above also ? My guess is that it has to do with react Life Cycles . Thanks so much !
Solution 1:[1]
The main difference comes down to re-rendering.
Variables set outside of the component will not trigger a re-render, whereas those that are set inside a component will trigger a re-render.
In general you wouldn't set a constant inside of a component for this reason... if you have a constant, put it in a constants file and call as needed - that way you won't have any unintended re-renders.
If you need the variable to update, then use the useState
hook to manage this:
const [name, setName] = useState('Tom');
When you update name
using setName('New Name')
it will trigger a re-render.
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 | John Detlefs |