Why in React I can not retrieve data from useState without distructuring?

Viewed 43

Why in React I can not retrieve data from useState without distructuring? Like this:

const name = useState('kana')[0];
const setName = useState('kana')[1];

I know I can do it like this:

const stateName = useState('kana')
const name = stateName[0];
const setName = stateName[1];

but why I can not do it like I did in first example??

1 Answers

The problem with the first example is that you're calling useState twice. When you do that, React is creating and managing two entirely different pieces of state. As a result, the "name" variable and the "setName" function are entirely separate.

Your 'name' const on the first line has no way to be updated.

Related