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;