loading...

useState or const: what's the difference?

wolfhoundjesse profile image Jesse M. Holmes ・1 min read

Here's a quick bite for you. What are the differences between these two declarations?

const Tuesday = () => {
  const [needsTacos] = React.useState(true); // 1
  const needsTacos = true; // 2
  return <marquee>Of course we need tacos!</marquee>
}

Discussion

pic
Editor guide
 

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.

 

Right? I havent found a reason to use

const [variableOnly] = useState()

or

 const [,setterOnly] = useState()

I just thought it was a fun thinking exercise.

 

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!

 

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

 

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

 

Yes, you are right, Ryan.

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

 

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))

 

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