How can you work with an object in React Hooks useState

0 votes
With the help of code can i know How can you work with an object in React Hooks' useState?
Mar 12 in Node-js by Ashutosh
• 23,230 points
60 views

1 answer to this question.

0 votes

In React Hooks, useState can store and manage objects. Here's how you can work with an object in useState:

Initialize state with an object:

const [state, setState] = useState({ key1: value1, key2: value2 });

Update the object:

Use the spread operator (...) to merge the existing state with new values, ensuring other properties are preserved.

setState(prevState => ({ ...prevState, key1: newValue }));

Access object properties:

Access properties directly from the state object.

const value = state.key1;

Example:

import React, { useState } from 'react';

function App() {

  const [user, setUser] = useState({ name: 'John', age: 30 });

  const updateName = () => {

    setUser(prevUser => ({ ...prevUser, name: 'Jane' }));

  };

  return (

    <div>

      <p>Name: {user.name}</p>

      <p>Age: {user.age}</p>

      <button onClick={updateName}>Update Name</button>

    </div>

  );

}

export default App;

answered Mar 12 by Tanvi

Related Questions In Node-js

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How do you model a many-to-many relationship in MongoDB with an example?

In MongoDB, a many-to-many relationship can be ...READ MORE

answered Feb 23 in Node-js by Kavya
104 views
0 votes
1 answer

How to add an element to a useState array in React?

You can use the spread operator (...) ...READ MORE

answered Mar 12 in Node-js by Tanvi
43 views
0 votes
1 answer

How to use async functions effectively in React components?

To use async functions effectively in React ...READ MORE

answered Mar 12 in Node-js by Sahil
60 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How does Babel differ from JSX?

Feature Babel JSX Definition A JavaScript compiler that transforms ES6+ code ...READ MORE

answered Mar 12 in Java-Script by Sahil
95 views
0 votes
1 answer

How can I initialize state with props in React using hooks?

You can initialize state with props using ...READ MORE

answered Feb 12 in Node-js by Navya
114 views
0 votes
1 answer

How can you preload data for a route in React?

Preloading Data for a Route in React ...READ MORE

answered Feb 24 in Node-js by Kavya
133 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP