React JS State Challenge: Master useState with Objects - Test Your Skills 🧑💻
React JS State Challenge: Master useState with Objects - Test Your Skills 🧑💻
Managing state in React is essential, especially when dealing with objects. The useState
hook can store objects, and updating state correctly is key to avoiding common pitfalls.
Challenge: Updating Object State
- Given an object in state, how do you update only one property without affecting others?
- React state updates should always be immutable.
- Using the spread operator ...
is a common technique.
Example Code
import React, { useState } from "react";
function UserProfile() {
const [user, setUser] = useState({ name: "John", age: 25 });
const updateAge = () => {
setUser(prevUser => ({ ...prevUser, age: prevUser.age + 1 }));
};
return (
Name: {user.name}
Age: {user.age}
);
}
Can You Solve This?
- Try adding another property, like email
, and update it without modifying the rest of the state.
- How would you handle nested state objects efficiently?