How to set an object key inside a state object in React Hooks?


The React component can contain various states, and we can use state variables inside the return statement with HTML elements. Whenever the value of state variables updates, it also updates on the web page without refreshing the web page.

This tutorial will teach us to use the objects inside the state variable. Whatever value like number, string, Boolean, or object we want to store in the state variable, we need to pass it as a parameter of the useState() hook.

Use the objects in the React hooks

This section will teach us to use an object as a value in the React hooks. We will initialize the state variable with an object containing the different properties with its value. After that, we can update the property value of objects and use the setState() function to set the updated object.

Syntax

Users can follow the syntax below to use the object key inside the state object in React hooks.

const [objState, setObjState] = useState({ a: 10, b: 76676, c: "Welcome" });
setObjState({ ...objState }); 

In the above syntax, we have passed the object as a parameter of the useState() method. Also, the user can see how we have used the setObjState() function to update the object.

Example

In the example below, we have used the functional components to set objects in the React hooks. We used the useState() hooks to create states in React. We have added three properties called a, b, and c with different values as a state object.

Whenever the user clicks the button, it executes the updateValues() function, which changes the properties of the objState object and uses the spread operator by taking the objState as an operand with the setObjState() function.

import React, { useState } from "react";
export default function App() {
   const [objState, setObjState] = useState({ a: 10, b: 76676, c: "Welcome" });
   function updateVales() {
      objState.a = 20;
      objState.b = 30;
      objState.c = "Hello";
      setObjState({ ...objState });
   }
   return (
      <div>
         <h2>
            {" "}
            Using the <i> objects inside the state object </i> in React hooks.
         </h2>
         <h3> The object property and values are </h3>
         <h4> a :- {objState.a} </h4>
         <h4> b :- {objState.b} </h4>
         <h4> c :- {objState.c} </h4>
         <button onClick = { updateVales}> Update object property values </button>
      </div>
   );
}

Output

When you click on the "Update object property values", it will display Example 2

Example

In the example below, we have used the useState() hooks and created the mousePos state variables. The setMousePos() function is used to update the value of the mousPos state.

In the HTML, we have used the onPointerMove() event to get the mouse pointer's current location on the web page. Whenever the user moves the mouse pointer, it will trigger the event and invoke the setPointer() function, which updates the x and y property value of the mousePos object.

import React, { useState } from "react";
export default function App() {
   const [mousePos, setmousePos] = useState({ x: 0, y: 0 });
   function setPointer(event) { 
      mousePos.x = event.clientX;
      mousePos.y = event.clientY;
      setmousePos({ ...mousePos });
   }
   return (
      <div onPointerMove = {setPointer} style = {{ height: "100vh", width: "100%" }}>
         <h2>
            {" "}
            Using the <i> objects inside the state object </i> in React hooks.
         </h2>
         <h3> The object property and values are </h3>
         <h4> x :- {mousePos.x} </h4>
         <h4> y :- {mousePos.y} </h4>
      </div>
   );
}

Output

Use the array object in the React hooks

We can also use the array as a state variable while using the React hooks. In this section, we will use the array of objects as an initial value of the state variable. After that, we will access every object of the state array and update their property values according to the requirements.

Syntax

Users can follow the syntax below to use the array of objects as a state with React hooks.

const [arrayOfObj, setArrayObjects] = useState([
   { prop1: "value1", prop2: "value2" },
]);
setArrayObjects([...arrayOfObj]); 

In the above syntax, users can observe how we have used the useState() hook to initialize the state variable with an array of objects. After that, we also used the setArrayOfObj() function to set the updated array.

Example

In the example below, the arrayOfObj state variable contains four objects with different key-value pairs as an initial value.

Whenever the user clicks the update values button, it invokes the updateValues() function, which changes the value of the ‘prop1’ property of every object of the array. After that, we used the spread operator to update the value of the arrayOfObj state variable.

Users can see the updated value of object properties after pressing the button.

import React, { useState } from "react";
export default function App() {
   const [arrayOfObj, setArrayObjects] = useState([
      { prop1: "value1", prop2: "value2" },
      { prop1: "Hello", prop2: "World!" },
      { prop1: "Your", prop2: "welcome" },
      { prop1: "Hi", prop2: "There!" },
   ]);
   function updateValues(event) {
      arrayOfObj[0].prop1 = "new_value1";
      arrayOfObj[1].prop1 = "new_value2";
      arrayOfObj[2].prop1 = "new_value3"; 
      arrayOfObj[3].prop1 = "new_value4";
      setArrayObjects([...arrayOfObj]);
   }
   return (
      <div>
         <h2>
            {" "}
            Using <i> array objects inside the state object </i> in React hooks
         </h2>
         <h3>The object property and values are </h3>
         <h4>
            {" "}
            prop1 :- {arrayOfObj[0].prop1} , prop2 :- {arrayOfObj[0].prop2}{" "}
         </h4>
         <h4>
            {" "}
            prop1 :- {arrayOfObj[1].prop1} , prop2 :- {arrayOfObj[1].prop2}{" "}
         </h4>
         <h4>
            {" "}
            prop1 :- {arrayOfObj[2].prop1} , prop2 :- {arrayOfObj[2].prop2}{" "}
         </h4>
         <h4>
            {" "}
            prop1 :- {arrayOfObj[3].prop1} , prop2 :- {arrayOfObj[3].prop2}{" "}
         </h4>
         <button onClick = {updateValues}> Update values </button>
      </div>
   );
}

Output

When you click the “Update values” button, it will produce the following result

Users learned to set the object as an initial value in React hooks. Also, users learned to update the object's property values using React hooks. In the last example, users learned to use the array of objects with React hooks and update the value of every object of the object’s array.

Updated on: 28-Feb-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements