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)
?
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With