0

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

2 Answers 2

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"
  }
})
Sign up to request clarification or add additional context in comments.

Comments

0

try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.