Why in one function state is updated immidietly and in other isn't

so I know that setState() is asonchrynus but I don’t understand when It is. I always run into this problem when mapping lists in react. Specifically when I delete list element.
This function updates state instantly and rerenders array.map() function:

const handleHistoryDel = (index) => {
    setHistory(history.filter((_, i) => i !== index));
  };

And this one updates state but doesn’t rerender:

const handleHistoryDel = (index) => {
    let temp=history;
    temp.splice(index,1)
    setHistory(temp);
  };

What is the difference? Should second function use some kind of callback? If so how would you implement one?

>Solution :

This happens because temp has the same memory address reference, when you run array.filter you get a new array, allocated in another space.

when you write let temp = history; you get the same reference, React will compare the previous state with the current one, if they have the same reference, it will not re-render.

try yourself:

const handleHistoryDel = (index) => {
  let temp = [...history];
  temp.splice(index,1)
  setHistory(temp);
};

Leave a Reply