Nat
Nat

Reputation: 23

How to avoid mutating state when updating a property

I have a function that when it is called is passed the initialState and the function to update the state (set through react hooks)

const [initialState, setInitialState] = useState("name")

const toggleValue = (initialState, setInitialState) => {
   const myVal = initialState;
   myVal["name"] = "This is a new name"
}

My expectations were that reassigning the state to a variable would not cause the state to be mutated when that variable was updated.

However I’m noticing that when I run toggleValue initialState is changing to "This is a new name" as well as myVal. Is there a way to avoid mutating the state? My goal is to update a property in the initialState object and then update the state.

Upvotes: 0

Views: 55

Answers (1)

ravibagul91
ravibagul91

Reputation: 20755

First thing is your state is not an object, it is simple string value,

const [initialState, setInitialState] = useState("name")

Updating string value is very simple,

const toggleValue = (initialState, setInitialState) => { 
   setInitialState("This is a new name") //This will simply change the state
}

If your state is an object like,

const [initialState, setInitialState] = useState({name:"name"})

In that case you can change the state like,

const toggleValue = (initialState, setInitialState) => {  
   const myVal = {...initialState}; //This will create a copy
   myVal["name"] = "This is a new name";

   setInitialState(myVal); //This is needed to update the state.
}

Demo

Upvotes: 1

Related Questions