score:2

Accepted answer

It's not recommended to modify the state itself because it is immutable.

So instead using .pop() on the original state of the array, first I suggest to clone that one and remove the required element from there, then the result should passed to setList() function.

Try as the following instead:

const remove = () => {
    const copy = [...list];
    copy.pop();
    setList(copy);
}

Think about the following:

const list = [1,3,5,6,7];
const copy = [...list];
copy.pop();

console.log(list);
console.log(copy);

I hope this helps!

score:2

You need to set a new array in this case, setList(list) will not cause React to re-render because it's still the same array you're using.

Try setList([...list]) in your remove function.

There's also an alternative to pop, and doesn't mutate the original variable:

  const remove = () => {
    const [removed, ...newList] = list
    setList(newList)
  }

Related Query

More Query from same tag