Sooyeon
Sooyeon

Reputation: 81

In React Hook, how can I change specific value of useState array?

  let [_value, setValue] = useState([1, 2, 3, 4, 5, 1, 2, 3, 4, 5 ]);

In this code, if I want to change the _value[3] how can I change value using setValue?

In my project, I have to change the _value[index] when the (rating) button is clicked.

So I have to dynamically change the _value[index].

If you know the answer, please let me know. Thank you!

Upvotes: 5

Views: 5967

Answers (2)

Nick
Nick

Reputation: 16576

There are generally a couple ways to update arrays in JavaScript. Importantly, whatever you do, you want to make sure you don't mutate the existing state.

One way is to make a shallow copy of the array, mutate the copy, and set the new state:

function update(index, newValue) {
  // shallow copy
  const newArray = [..._value];
  // mutate copy
  newArray[index] = newValue;
  // set state
  setValue(newArray);
}

Another option is to map over the array, returning the new value when the index matches the desired index.

function update(index, newValue) {
  const newArray = _value.map((v, i) => {
    if (i === index) return newValue;
    return v;
  });
  setValue(newArray);
}

Upvotes: 8

Drew Reese
Drew Reese

Reputation: 202638

In React you need to return a new state array reference. You can achieve this by mapping the previous state to the next state, using the index to match by, when the index matches return the new value, otherwise return the current value.

const updateByIndex = (newValue, index) => {
  setValue(values => values.map((value, i) => i === index ? newValue: value);
};

Upvotes: 4

Related Questions