Easy Steps to Using React useState Hooks with Object

useState with Object

In this article, we will see the example of useState hooks with the object as a state variable in React JS. Let’s see the example code:

Example of object useState hook

Ex:

import React, { useState } from 'react';
import  ReactDOM  from 'react-dom';

function Hookcounter(){
  const[name,setName] = useState({firstName:'', lastName:''})
  return(
    <div>
      <input type='text' value={name.firstName}
      onChange={e => setName({ firstName: e.target.value })} />
      <input type='text' value={name.lastName}
        onChange={e => setName({ lastName: e.target.value })} /> 
         <h2>Your first name is : {name.firstName}</h2>
         <h2>Your last name is : {name.lastName}</h2>
        </div>
       )}

Output:

usestate with object

Steps:

  1. In the above code, we have imported the useState hook from ‘react’.
  2. Then we created the function component Hookcounter().
  3. Within the component, create a constant “name“, “setName” and assigned them to “useState()“. The default value will be an object, the object will contain firstName and lastName, initialize to an empty string. So, this is an important point to keep in mind. A state variable can be a string, number, boolean, object, or even an array. You can use any of those types based on your requirement.
  4. In the render function, we basically want to have two <input> fields one for “firstName” and another for “lastName”. Below the input fields, we simply display the “firstName” and “lastName” using <h2> tag
  5. Next, let’s handle the “value” attribute and the “onChange” Event on two <input> fields. We set the “value” attribute to “{name.firstName}” for the first <input> field and the “value” attribute to “{name.lastName}” for the second <input> field. Input “onChange” attribute is used whenever the user starts typing in something, we want to set the firstName property. So, we set the “onChange” attribute to “{e => setName({firstName: e.target.value})}” for the first <input> field, similarly, we should set “lastName” for the second input field.
  6. So, whenever the first input field value changes, we update the “firstName” property, and when the second input field value changes, we update the “lastName” property.
  7. See the below output, if we start the firstName input field, the lastName property disappears from the state variable, and if we start the lastName input field the lastName property disappears from the state variable. The reason this happens is that useState() hooks don’t automatically merge and update the object.
READ ALSO  Top 5 Static Analysis Tools to Boost Your React App

This is the key difference to setState which you come across in class components. setState will merge the state, whereas the useState hook set of functions will not merge the state, you have to do it manually. It’s not difficult though because we can use the spread operator to handle the manual merge.

Change that:

<input type='text' value={name.firstName}
onChange={e => setName({ ...name, firstName: e.target.value })} />
<input type='text' value={name.lastName}
onChange={e => setName({ ...name, lastName: e.target.value })} />

Output:

usestate with object

In the above code, we change the “onChange” attribute to spread the name and then overwrite firstName and lastName. It copies every property in the object and then overwrites the firstName field with a different value. Similarly, the “lastName”, makes a replica of the “name” object and then updates the lastName property to the new value. Now, see the above output, our firstName, and lastName is displayed successfully.

The spread operator is a feature of ES6 and is a very common operator in use now. If you’re new to this do spend a few understanding the spread operator.

Leave a Reply