React Hooks useState() with Object

React Hooks useState() with Object

React Hooks have revolutionized the way we write functional components in React. One of the most commonly used hooks is useState(), which allows us to manage state within our functional components. While useState() is typically used with primitive data types like strings and numbers, it can also be used with objects.

Using useState() with objects is straightforward. We can define an initial state object and update it using the setState function returned by useState(). Let’s take a look at an example:

import React, { useState } from 'react';

const App = () => {
  const [user, setUser] = useState({ name: '', age: 0 });

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setUser((prevState) => ({ ...prevState, [name]: value }));
  };

  return (
    
Name: {user.name} Age: {user.age}
); }; export default App;

In the example above, we define a state variable called “user” using useState(). The initial state object has two properties: “name” and “age”. We also define a handleInputChange function that updates the “user” state object whenever the input fields change.

Inside the handleInputChange function, we destructure the “name” and “value” from the event.target object. We then use the setUser function to update the “user” state object. To ensure immutability, we spread the previous state using the spread operator (…) and update the specific property using computed property names ([name]: value).

In the return statement, we render two input fields bound to the “name” and “age” properties of the “user” state object. We also display the current values of “name” and “age” using interpolation.

By using useState() with objects, we can easily manage complex state structures within our functional components. This approach allows for more flexibility and maintainability in our React applications.

That’s it! You now know how to use useState() with objects in React Hooks. Give it a try in your next project and experience the power of functional components.


Posted

in

by

Tags:

Comments

Leave a Reply

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