Course contentsShow
← React
Lesson 1762 of 2,39641. State Management EcosystemFree lesson

Direct Mutations vs Immutable Updates

Why Valtio allows direct mutations (state.count++) unlike React's useState, and when this pattern shines.

Direct Mutations vs Immutable Updates

You'll learn why Valtio's mutable style (state.count++) differs fundamentally from React's immutable pattern (setState(prev => prev + 1)), and when mutating directly becomes a superpower.

The React Way: Immutability Required

In standard React with useState or useReducer, you must create new objects to trigger re-renders:

// React requires this immutable pattern
const [user, setUser] = useState({ name: 'Alice', age: 30 });
setUser({ ...user, age: 31 }); // New object reference

React compares references (oldState === newState). If they're the same, no re-render happens. This forces you to spread, clone, or use libraries like Immer.

The Valtio Way: Mutate Freely

Valtio's proxy-based tracking watches which properties you access and change. You can mutate directly:

import { proxy } from 'valtio';

const state = proxy({ name: 'Alice', age: 30 });

// Just mutate it
state.age = 31; // Components re-render automatically

The proxy intercepts state.age = 31, detects the change, and notifies subscribed components. No spreading, no new objects.

Why This Matters

Analogy: React is like a librarian who only notices when you return a different book. Valtio is like a security camera that sees you editing pages inside the same book.

When Valtio's pattern shines:

  • Deeply nested state (state.user.address.city = 'Boston' just works)
  • Rapid prototyping without immutability boilerplate
  • Performance-critical updates where creating new objects is wasteful

When to stick with immutability:

  • You need explicit control over what changes
  • Your team prefers predictable, traceable updates
  • You're using Redux, Zustand, or other immutable-first tools

Key Takeaway: Valtio's direct mutations (state.count++) are safe because proxies track changes automatically—unlike React's useState, which requires new references to detect updates. This makes Valtio ergonomic for complex nested state.