DEV Community

Ahmet Meliksah Akdeniz
Ahmet Meliksah Akdeniz

Posted on • Updated on

useState | One of the Most Common Hooks that You Will Be Using in React -Objects as State Values

Hello folks, today I will continue talking about useState hook in React. Previously, we've covered what it's, how to use it, and we gave some use cases with data types such as strings and arrays. In this post, I will be talking about how to work with objects using useState hook. Click here to read previous part

Here's the whole code, afterwards I will explain it in small chunks:

import { useState } from "react";

const JobUpdaterComp = () => {
  const [person, setPerson] = useState({
    name: "Ahmet Meliksah",
    age: 24,
    job: "customer representetive",
  });

  const updateJob = () => {
    setPerson({ ...person, job: "junior React developer" });
  };

  return (
    <div>
      <h1>Name: {person.name} </h1>
      <h1>Age: {person.age} </h1>
      <h1>Occupation: {person.job} </h1>

      <button
        onClick={updateJob}
        style={{
          padding: "1rem",
          borderRadius: "1rem",
          border: "none",
          backgroundColor: "rebeccaPurple",
          color: "white",
          cursor: "pointer",
        }}
      >
        Update Occupation
      </button>
    </div>
  );
};

export default JobUpdaterComp;
Enter fullscreen mode Exit fullscreen mode

import { useState } from "react"; first of all, import useState from React. After that, create a value called person, and assign an object to it like so:

const [person, setPerson] = useState({
    name: "Ahmet Meliksah",
    age: 24,
    job: "customer representetive",
  });
Enter fullscreen mode Exit fullscreen mode

In object above, we've got name, age and job keys. And say, we want to update the 'job' key in this object. Do you think this is the right solution?

const updateJob = () => {
    setPerson({ job: "junior React developer" });
  };
Enter fullscreen mode Exit fullscreen mode

Code above will update the 'job' key. However, it will remove name and age keys. Why? Because setPerson is a function that updates person's value. Once it's written as setPerson({ job: "junior React developer" });, we update job and update as if other keys do not exist. That's why, when updating objects in state if we want to preserve other keys (most of the time we do want to preserve them), we need to write them again. Or we can destructure, well I will destructure as usual, like so:

const updateJob = () => {
    setPerson({ ...person, job: "junior React developer" });
  };
Enter fullscreen mode Exit fullscreen mode

In the code above, { ...person, job: "junior React developer" } this part means; give me everything in 'person' object as they're, except 'job' key. Update job key to "junior React developer"

Code below, does the exact same thing as code above:

const updateJob = () => {
    setPerson({name: "Ahmet Meliksah", age: 24, job: "junior React developer" });
  };
Enter fullscreen mode Exit fullscreen mode

Yes, when objects are this small, it's somewhat ok not to destructure ({...person}). Unfortunately, most of the time this is not the case.

Our final part of code:

return (
    <div>
      <h1>Name: {person.name} </h1>
      <h1>Age: {person.age} </h1>
      <h1>Occupation: {person.job} </h1>

      <button onClick={updateJob}>
        Update Occupation
      </button>
    </div>
  );
Enter fullscreen mode Exit fullscreen mode

As you see, I access to object by this syntax object.key ({person.name}, {person.age}, {person.job}). Bear in mind, objects cannot be rendered in React, thus we've to use this syntax (object.key) in order to get object values. Finally, we've got a button that triggers updateJob function on click (onClick).

To sum it up, be careful with objects in states because we want to preserve other keys. So, when updating them, use destructuring method.

Top comments (0)