To update a state in React is a very simple process using react hooks - useState. Check the code below:

Update simple state

// import useState hook 
import React, {useState} from 'react';

//create and export the component
export default function MyName(){

//declare state as myName and state changing function as setMyName with useState()
// we set the value as an empty string here
const [myName, setMyName]= useState("");

// create a function that will update the state, here onChangeMyName
// we'll use this to our input field 
function onChangeMyName(e){
setMyName(e.target.value);

// above, setMyName will change the state value of myName when we will type
// in our input and it will receive the targeted/focused/typed element value
// that is written above as e.target.value
}

return(
    <div>
       <input type="text" onChange={onChangeMyName}/>
    </div>
  );
}

So, now if you declare a state named firstName, this is the process/code to update that state

const [firstName, setFirstName]=useState("");

function onChangeFirstName(e){
 setFirstName(e.target.value)
}

And, if you declare a state named lastName? The same way you can update it

const [lastName, setLastName]=useState("");

function onChangeLastName(e){
 setLastName(e.target.value)
}

Update object state

But, what if you have all those in one object, how will you update that? See this example

// here the value of person state is an object containing multiple properties
const [person, setPerson]=useState({
    firstName:"",
    middleName:"",
    lastName:""
});

This type of code creates a problem if we want to update the state like the above ways. Let's see the issue

function onChangeFirstName(e){
// this is invalid
setPerson({firstName:e.target.value});
// because this will replace the whole object of person state to only this 
// person = {firstName:"some-value-here"}; and middleName & lastName will no longer exist for the receiving state value
}

So, here is a solution for such issues, where all the properties will remain, but only the target will get updated

function onChangeFirstName(e){
// here first we will take a copy of the person state, then we'll only update firstName
setPerson({...person, firstName:e.target.value})

// updated person state is person={firstName:"some-value-here", middleName="", lastName:""}
// Now it's so clear
}

// the same way we can update other properties what we need
function onChangeLastName(e){
setPerson({...parson, lastName:e.target.value})

// for the second time it will return like this
// person = {firstName:"some-value-here", middleName="", lastName:"some-value-here"}
}

Read more on Reactjs here


If you find this post helpful, please feel free to share it