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

Time:07-29

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?

CodePudding user response:

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);
};

CodePudding user response:

Maybe pass a function inside the setState like this,

setHistory(prev =>  // Do some changes here and return it  //   )
setHistory(prev => [...prev])

Also refer to this answer that explains about immutablity

How does React useState hook work with mutable objects

CodePudding user response:

You should create a new array without reference to the state's array. And then mutate the newly created array.

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