React reload on setState of an array

All we need is an easy explanation of the problem, so here it is.

I just started with react and next. I was wondering why the value is reloading on the webpage when I update a useState like this [test, setTest] = useState("test"), but not in the case below. Can anyone explain why and how to fix it?

const [testing, setTest] = useState({
        name:"test"
    })

    function test(){
        setTest(old =>{
            old.name = "new name"
            return old;
        })
    }

    return (
        <ThemeProvider theme={theme>
            <button onClick={test} />
            <GlobalStyles/>

            <h1>{testing.name}</h1>
        </ThemeProvider>
    )

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

One of the core principles of react is that state is immutable. After you set state, react is going to do a === between the old state and the new state. If that results in true, then react believes that nothing has changed and skips rendering. Since you are mutating the state, it will pass an ===, and react cannot tell that you mutated the object.

So instead of mutating the state object, you will need to create a new one:

setTest(old => {
  return {
    ...old,
    name: "new name"
  }
})

Method 2

try

 function test(){
            setTest({...testing,name : "new name"})
        }

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply