Rollie
Rollie

Reputation: 4752

Can local state be variable?

Kinda a silly question, but normally I see

const [name, setName] = useContext(myContext)

but I have code where I want to do something like:

var [name, setName] = useContext(myContext)
useEffect(() => {
  if (someCondition)
    name = undefined

  setName(name ?? getName())
}, [name])

I always see that the state is labeled 'const', but does that matter? (the above could be refactored such that it doesn't matter, but this question is specifically regarding whether the 'var' vs 'const' practically matters)

Upvotes: 1

Views: 169

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370879

React generally practices functional programming, in which variables do not get reassigned, and state does not get mutated. Instead, when an update needs to occur, the entire function runs anew with the updated values returned by the useState (or useContext) calls.

In line with this, it usually makes code easier to understand at a glance when variables are declared with const - it'll help you remember this won't get reassigned, instead, the whole function will run again when an update occurs.

It's not outright forbidden to use var, but it could easily mislead you if you try to reassign the variable, since it almost certainly won't work as expected - the reassigned variable will only have that "state" of being reassigned as long as that render is active. Once the next render starts, the prior (or updated) name returned by useContext will be the new name, regardless of what name was reassigned to.

Best practice would be to avoid reassignment to avoid potentially confusing yourself. If you think you want to reassign a variable, you should probably reconsider and think about the more React way of doing things, which would likely involve setting state instead.

So state variables probably should not be reassigned - but other plain (non-React) variables could be, if it helps you implement the logic you need. (like let count = 4; or something, where count is local to a nested function and doesn't need to be stateful)

Upvotes: 3

Related Questions