frederik
frederik

Reputation: 199

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

Upvotes: 0

Views: 1563

Answers (2)

Nicholas Tower
Nicholas Tower

Reputation: 85221

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

Upvotes: 1

try

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

Upvotes: 0

Related Questions