🔗 Multi-Field Subscriptions

Subscribe to multiple fields with optimized re-rendering

User Info (Only re-renders on name or age changes)

Alice is 25 years old

Render count: 0

This increases when 'name' OR 'age' changes, but NOT when email changes!

💡 Tip: This demonstrates selective reactivity - only the fields you subscribe to will trigger re-renders.

✅ This component subscribes to ['name', 'age'] fields. Changing email won't trigger a re-render!

Test Controls

Current Store State:

{
  "name": "Alice",
  "age": 25,
  "email": "alice@example.com"
}

🧠 Smart Optimization

Multi-field subscriptions use shallow equality checks to prevent unnecessary re-renders:

  • Only re-renders if subscribed fields actually change
  • Uses custom distinctUntilChanged with shallow equality
  • Combines multiple observables efficiently with combineLatest
  • Cached snapshot functions prevent object recreation

Multi-Field Subscription

"use client";
function UserInfo() {
  // Only re-renders when name OR age changes
  const { name, age } = userStore.useFields(["name", "age"]);

  return (
    <p>{name} is {age} years old</p>
  );
}

Behind the Scenes

// Internally uses reactive optimization:
combineLatest(
  keys.map(k => 
    store.subjects[k].pipe(
      distinctUntilChanged(Object.is)
    )
  )
).pipe(
  map(() => ({ name, age })),
  distinctUntilChanged(shallowEqual)
)