0

I am fundamentally misunderstanding React hooks, especially the useState function. Why doesn't the code below update the index of the old array, and instead set the value of trick to 1? I understand how to push a new item onto an array with React hooks, but how do you update existing values?

const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}
1

3 Answers 3

1

If you provide modifyTrick a function, the return value will be the new value of trick.
The return value of your function is 1, so that's why trick is set to 1.

oldTrick[0] = 1 //this expression returns 1.

Modify oldTrick array in your modifyTrick function, and than return it:

const updatedTrick = () => {
    modifyTrick(oldTrick => {
       oldTrick[0] = 1

       return oldTrick;
    });
};
Sign up to request clarification or add additional context in comments.

4 Comments

Why is the return value 1?
@Perplexityy The assignment operator = also returns a value: the value you just set the variable to.
Think about the expression: 'x = y = 5;'. first y = 5 is executed, and returns the value 5. Because it returned the value 5, the next assignment (x = 5) is possible.
Interesting, I never knew that. Thanks!
1

Try this one

  const updatedTrick = () => {
    modifyTrick(oldTrick => {
      let newTrick = [...oldTrick];
      newTrick[0] = 1;
      return newTrick;
    })
  }

Comments

1

You can also do it like this:

const updateTrick = () => {
    modifyTrick(oldTrick => {
      oldTrick[0] = 1;
      return oldTrick;
    });
};

2 Comments

is the callback parameter not the reference
You're getting it wrong inside the function oldTrick is a new variable not the state one

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.