Categories
React Answers

How to update and merge state object using React useState hook?

Spread the love

Sometimes, we want to update and merge state object using React useState hook.

In this article, we’ll look at how to update and merge state object using React useState hook.

How to update and merge state object using React useState hook?

To update and merge state object using React useState hook, we can call the state setter function with a callback that returns the new object state value.

For instance, we write

const Comp = () => {
  const [state, setState] = useState({ fName: "", lName: "" });
  const handleChange = (e) => {
    const { name, value } = e.target;
    setState((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  return (
    <>
      <input
        value={state.fName}
        type="text"
        onChange={handleChange}
        name="fName"
      />
      <input
        value={state.lName}
        type="text"
        onChange={handleChange}
        name="lName"
      />
    </>
  );
};

to define the handleChange in the Comp component that calls setState with a callback that return an object with the prevState properties and the new property values.

We set the onChange prop to handleChange to get the input value from e.target.value and the name attribute value of the input from e.target.name.

Conclusion

To update and merge state object using React useState hook, we can call the state setter function with a callback that returns the new object state value.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.