user6377312
user6377312

Reputation:

React (Hooks) - Is it bad practice to set variables that are not suppose to change without useState?

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

Answers (3)

Anand Raj
Anand Raj

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

johnny
johnny

Reputation: 58

I don't think you need to apply useState here.

Upvotes: 0

benNek
benNek

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

Related Questions