0

I noticed that when I replace specific items in a data set and use a useState update it will only rerender on primatives.

Ex: this updates something but does not rerender

function TEST()
{
    const [something, setSomething] = useState(["this", "works", "?"]);

    return <div>
        <Button onClick={()=>{
            let tempSomething = something;
            tempSomething[1] = "can work";
            setSomething(tempSomething);
        }}>CHANGE</Button>
        {something}
    </div>
}

However, if you were to replace the parameter in setSomething() with either a literal or another created variable that does not link to something, then it will trigger a rerender. What is the issue here?

These work:

setSomething(["something", "new"]);

or

let r = ["why", "?"]
setSomething(r);
  • Because you're mutating the state. Never mutate state in React. – CertainPerformance Feb 24 '21 at 15:20
  • So you have to clone and then change the clone? How would I do it in this case? Things can get complex if the data type is of objects. –  Feb 24 '21 at 15:21
  • 1
    Yes, with objects, it can look messy, unfortunately. Easiest solution (but not the functional one) is to clone the array, find the index of the object, then reassign the object at that index with a new object – CertainPerformance Feb 24 '21 at 15:28
  • immer is a lightweight library for immutable changes with a less verbose api https://immerjs.github.io/immer/docs/introduction – azium Feb 24 '21 at 16:13

0 Answers0