Select Page

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

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

       <input type="text" onChange={onChangeMyName}/>

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

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

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

function onChangeLastName(e){

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({

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

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

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

Read more on Reactjs here

Go back to Tradecoder Dev Solution

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