I´m wrapping my head around the useState-Function of react and trying to implement sort of a simple copy-version for my own (just for learning purposes basically). I encounter a really silly problem I'm just stuck with. It´s probably so simple that I´m angry wih myself afterwards... :)
let state = []
const myState = (init) => {
state[0] = init
const setState = newState => state[0] = newState
return [state, setState] // return [state[0], setState] does not work
}
const [count, setCount] = myState(0)
console.log(count)
setCount(1)
console.log(count)
This version above does work, in fact I get logged out the state-array correctly: [0],[1]
But when I return [state[0], setState] in my myState-Function, I get: 0, 0
What is going wrong here? (I´m doing it with just node.js)
CodePudding user response:
In short words, the result you are getting is expected. It happens in this way, because state[0]
is a primitive value and when you return [state[0], setState]
from your myState
hook you just return the primitive value, which not updated anymore after this call myState(0)
.
When you return the whole state (return [state, setState]
) you return a link to this array, so that's why you are able to see updated values.
To dive deeper I'd recommend to learn how React renders components and updates the state. Without it, learning just how useState
works is not enough to get the whole picture.
React
works in a bit complex way, so after changing the state in the hooks, it internally triggers re-rendering and as a result you are getting the updated state in your components