Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading