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

React reload on setState of an array

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

>Solution :

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

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