DEV Community

useState or const: what's the difference?

Jesse M. Holmes on September 10, 2019

Here's a quick bite for you. What are the differences between these two declarations? const Tuesday = () => { const [needsTacos] = React.us...
Collapse
 
dechamp profile image
DeChamp • Edited

I'll bite... useState should be used with [needsTacos, setNeedsTacos] first off... since the whole purpose is to be able to manage the state. One is a constant value which never changes. So I feel like this is a trick question or I totally misunderstood it.

Collapse
 
wolfhoundjesse profile image
Jesse M. Holmes

Right? I havent found a reason to use

const [variableOnly] = useState()

or

 const [,setterOnly] = useState()

I just thought it was a fun thinking exercise.

Collapse
 
dechamp profile image
DeChamp

It is a fun thinking exercise, because I was racking my brain to see if i was missing something. It also leads in to letting others know that, yes you may think it's an option, but it's not the proper use. So maybe someone will see this and have the questions answered. Thumbs up!

Collapse
 
dance2die profile image
Sung M. Kim

// 1. needsTacos "can" trigger re-render.
// 2. needsTacos doesn't trigger re-render (same goes for ref by useRef)

Collapse
 
omgitsgod profile image
Ryan Penchenski

Wouldn't you need a "setNeedsTacos" to trigger a re-render?

Collapse
 
dance2die profile image
Sung M. Kim

Yes, you are right, Ryan.

Updating the state using setNeedsTacos "can" cause the re-render.

Collapse
 
revalenza profile image
Robert Valenzuela

thx this help me to understand the difference

Collapse
 
barreraslzr profile image
Emmanuel Barrera

I think you dont know how use hooks so... the hook are only like observables, and that's the way that are const because its just variables where i will push and pull values...

And like observables that variables have triggers that will be dispatched and make renders or active useEffects ( or more hooks ) because all the hook are like functions that are attached with observables, so the hook are just triggers attached to observables

so... i dont know why you have only the observables and not have the function to change that observable value, if you only wants to keep the values saved, you just need to have the const ( like the functions, because you dont need change the function value (i hope.. for the best practices be with you... xd))

Collapse
 
pickleat profile image
Andy Pickle

Second would throw an error if reassigned and the first could be updated if called, correct?