React Mastery / React Hooks

useState with Objects

🔹 What is useState with Objects?

In React, useState can store objects when you need to manage multiple related values together (like form data, user info, settings, etc.).

Instead of creating many separate states, you store them inside one object.


🔹 Basic Syntax

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

  • setState → function to update the object

  • ⚠️ Updating replaces the entire object (not merges)


🔹 Simple Example

🧠 What’s happening?

  • user stores an object { name, age }

  • Clicking button replaces the entire object with a new one


🔹 Updating Only One Property (IMPORTANT)

When updating one property, you must copy the previous object using the spread operator (...).

❌ Wrong Way

setUser({ name: "John" });

➡️ This removes age ❌

✅ Correct Way

setUser({
  ...user,
  name: "John"
});

➡️ Keeps age and updates name ✅


🔹 Example: Updating Individual Fields


🔹 Using Functional Update (Best Practice)

When new state depends on previous state, use a function.

setUser(prevUser => ({
  ...prevUser,
  age: prevUser.age + 1
}));

✅ Why?

  • Prevents bugs

  • Always gets latest state

  • Recommended in real apps


🔹 When to Use Object State?

✅ Use object state when:

  • Fields are related (forms, profiles)

  • Updating multiple values together

❌ Avoid when:

  • Fields update independently

  • Object becomes too large → split state


❌ Common Mistakes

Mistake

Result

Not using spread operator

Data loss

Mutating object directly

No re-render

Using stale state

Bugs