Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `useState(null)[1]` in React hooks?

I'm using React hooks now. I've seen useState(null)[1] but I forgot where I seen it.

I wonder what's different from useState(null)?

like image 654
Kexin Li Avatar asked Dec 22 '22 19:12

Kexin Li


1 Answers

In the docs, it says

Returns a stateful value, and a function to update it.

But what they mean is

Returns an array where the first position is a stateful value, and the second position is a function to update it.

The useState hook returns an array where the first position (index 0) is the state and the second position (index 1) is the setter for that state.

So when using useState(null)[1] you are only getting the setter for that state.

When you do

 const [state, setState] = useState(null)

What you are doing is called Destructuring Assignment

And because in most cases you want to have both state and setState, destructuring makes it much easier to use than doing.

const hook = useState(null)
const state = hook[0]
const setState = hook[1]

With destructuring, you can make that with only one line which is much cleaner

And if you only want the setter, you can do it by

const setState = useState(null)[1] // only getting the setter

Just keep in mind that both are the same thing.


I wonder what's different from useState(null)?

useState(null) returns an array ([state, setState])

useState(null)[1] is accessing the returned array (setState)

like image 134
Vencovsky Avatar answered Dec 26 '22 11:12

Vencovsky