How to Update and Merge State Object using React useState Hook?

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.

Update and Merge State Object using React useState Hook

To Update and merge state object using React useState hook, we can pass in a function into the state setter function.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount((count) => count + 1);
  };

  return (
    <div>
      <div>{count}</div>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

to create the count state with the useState hook.

And to make sure we update count by incrementing the current count value, we pass in a function that takes the current count value and return the new count value into the setCount state setter function.

Then we set that as the value of the onClick prop of the button to run increment when we click it.

Therefore, when we click the button, we see the count incremented by 1.

Conclusion

To Update and merge state object using React useState hook, we can pass in a function into the state setter function.