How to set object in useState with React Js

Using following steps we can use the objects in useState with React js

Import useState from React.
Initialize state with object.
Update the state using the onClick event handler .

Example-:

import React, { useState } from 'react';

const App = () =>{
  const [Obdetails, setObdetail] = useState({name: "BlogsHub", counter: 1})
function handleobject(){
  setObdetail((prev) => ({
    ...prev,
    counter: prev.counter+1
  }))
}
console.log(Obdetails)

  return (
    <>
     Name is -: {Obdetails.name} and Counter is-:  {Obdetails.counter}<br/>
     <button onClick={handleobject}>Handle Object</button>
    </>
  )
}

export default App;

Code explanation:

Import useState:
First import the useState from React.
import React, { useState } from ‘react’;

Initialize State:

const [Obdetails, setObdetail] = useState({name: “BlogsHub”, counter: 1})
Initialize State with the object value, setObdetail Value function is used for update the state and Obdetails variable is used to assign the objects value.

Bind State to Input:

Handle Object:
handleobject function call on button click event to handle object values

Get the Previuos Data:
Inside the setObdetail “prev” is used for hold the previous data if we will not use the “prev” it will replace old value of the object

setObdetail((prev) => ({
    ...prev,
    counter: prev.counter+1
  }))

Output:

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *