Reputation:
Is it bad practice to set a variable that is not suppose to change (that for example I need in a method and need to take it out of that function scope) like in the code below?
const App = () => {
const [counter, setCounter] = React.useState(0)
const staticNum = 51;
return (
<div></div>
)
}
Doing something like:
const [staticNum, setStaticNum] = React.useState(51)
seems like a waste as I would never call setStaticNum as staticNum is not suppose to be changed
Upvotes: 0
Views: 313
Reputation: 443
UseState should be used to store variables whose value change should re-render the component
If the value of a variable does not change, then there is no need to store it in the component state
If you use UseState for static variables, then it only adds additional overhead to the component
Upvotes: 0
Reputation: 58
Yes, there is no point of having those in useState
. Besides, if the value is the same on every rerender, you could move it above the function, so the value won't be initialized on every rerender. This only matters with functions and objects tho, but still a good practice to keep in mind
Upvotes: 2