How can I change only one property of an object using the useState hook

Asked

Viewed 1,390 times

1

I wonder how I can change only a specific property of an object using the useState hook

const [value, setValue] = useState({value1: "abc", value2: "abcd"})

How would it be possible to change only the value1 remaining the state of value2?

1 answer

5


You can use the Operator spread when updating the value in the State. It would look like this:

setValue(prevState => {
    return { ...prevState, value1: "novo valor" }
});

This way the value2 continues with the original value

  • Thank you very much! I also realized that my function (setValue) was inside a useCallback and I had not passed the state as it depended on that callback, so soon it did not change :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.