useState with object in React Hooks

Today we’ll show you how to use the useState with object in React Hooks. When we are dealing with the object in the state variable then we have to manage the object in different ways using React Hooks.

Let’s take a simple example to manage the user information such as name, email, and age in state variable using React Hooks.

If you are new in react hooks then I will recommend you to check the following articles to understand the Hooks.

React Hooks for Beginners

useState with object in React Hooks

  1. Create a react application
  2. Add HTML element to prepare UI
  3. Add logic to manage object using useState
  4. Output

1. Create a react application

First of all we will have a startup react application to implement the demo. Here, we’ll use the create-react-app NPM Package. Run the following command to create a startup app.

2. Add HTML element to prepare UI

As we are planning to collect the user information so we will add the three input elements i.e. name, email, and age. We have added the following code in the App.js component.

3. Add logic to manage object using useState

Let’s write logic to manage the object in the state variable. The handling objects in state variables using Hooks is slightly different than the setState method.

When we pass the updated state then setState will merge the state where the useState will assign a new state so that it does not merge the state.

Therefore we will manually merge the state by spreading the object in Hooks. Check out the following code to update the object in the state variable using Hooks.

App.js

Here, we have used the previous state to update the state value. Check out the link below for more insight.

useState with the previous state in React Hooks

4. Output

Run the application and check the output in the browser.

Output - useState with object in React Hooks - Clue Mediator
Output – useState with object in React Hooks – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *