'Closure-Mistake index of array in self-implemented useState-Function (for learning purposes)

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)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source