What would be the implementation for the code in Vanilla JS that allows us to declare and update state like the way useState does so in React:
const [x, setX] = useState(12);
setX(14);
console.log(x); // 14
This question is strictly get better at JS. Naively it would make sense to go with:
// Solution 1
function update(value, newValue) {
value = newValue;
return value;
}
function state(value) {
return [ value, update ];
}
let [value, setValue] = state(12)
value = setValue(value, 14)
console.log(value); // 14
// Solution 2
class State {
constructor(value) {
this.value = value;
}
update(newValue) {
this.value = newValue;
}
}
const x = new State(12);
x.update(14);
console.log(x.value); // 14
But I don't understand how the array [x, setX] has a callback (setX) that can affect x when declared with a const? I hope that makes sense.