Course contentsShow
← React
Lesson 386 of 2,39611. useState Patterns and PitfallsFree lesson

Migration Path: Refactoring Between Patterns

Practice converting multiple useState calls to a single object and vice versa without breaking behavior.

Migration Path: Refactoring Between Patterns

You'll learn how to safely transform state structure from multiple useState calls to a single object (or back) without breaking your component's behavior.

The Core Challenge

You've seen both patterns: multiple useState calls for independent values and a single object holding related state. In real projects, you'll need to refactor between them as requirements evolve. The trick is doing it without introducing bugs.

The Step-by-Step Approach

From Multiple useState to Single Object:

  1. Identify which state values are related (change together, represent one concept)
  2. Create a new useState with an object containing all those values
  3. Update every setter call to use the spread operator pattern
  4. Replace every state read with object property access
  5. Delete the old useState calls

From Single Object to Multiple useState:

  1. Add individual useState calls for properties you want to separate
  2. Update reads to use the new variables instead of object properties
  3. Replace object setters with individual setter calls
  4. Remove the object useState and any spread operations

Think Like a Surgeon

Imagine carefully separating conjoined twins or joining separate systems. You can't rush—each connection must be handled deliberately. Test after each small change. Your component should work identically before and after the refactor.

The safest path: make the change in small commits. Add the new structure while keeping the old, verify everything works with both, then remove the old structure.

Key Takeaway: Refactoring state structure is safe when done incrementally—add the new pattern, verify behavior, remove the old pattern. The component's external behavior should never change, only its internal organization.