0

Why doesn't this function work like the useState() hook from react?

const myState = val => {
  let value = {
    val,
    set setVal(newVal) {
      this.val = newVal;
    }
  };

  const setValue = newVal => {
    value.setVal = newVal;
  }

  return [value.val, setValue];
}

const [myVal, setMyVal] = myState("initial value");

console.log(myVal);
setMyVal("updated value");
console.log(myVal);

Expected output:

initial value
updated value

Actual output:

initial value
initial value
17
  • 2
    I'm not real familiar with this type of coding, but why would you define a variable to be a const, and then expect it's value to change? that doesn't seem right. Commented Jun 22, 2020 at 20:03
  • 1
    @Rick Yes, that's a point most people miss. A const cannot change its value. Just because its part of a state hook doesn't change that fact. Instead, react sets the const to the updated value on the next render, so the const never changes values, but is instead destroyed and re-created. Commented Jun 22, 2020 at 20:05
  • 1
    There's a lot of things wrong in that code, but even if you make it work exactly like useState in React, it would still print "initial value" twice because that's what React's useState would also do. Commented Jun 22, 2020 at 20:09
  • 2
    React hooks are not this straight forward. They have complex implementations. For starters, the function component is executed again, the variables are recreated with new values after setValue is called Commented Jun 22, 2020 at 20:11
  • 1
    Here's a simplified version Commented Jun 22, 2020 at 20:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.