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

Atom Families for Dynamic Collections

Using atomFamily to create parameterized atoms for managing lists or keyed collections efficiently.

Atom Families for Dynamic Collections

What you'll learn: How to use atomFamily to dynamically create atoms for managing lists or keyed collections without performance bottlenecks.

The Problem with Static Atoms

Imagine you're building a todo app. You could store all todos in one big atom, but then every component reading any todo re-renders when any todo changes. You need separate atoms for each todo, but how do you create atoms dynamically as todos are added?

What is atomFamily?

An atom family is a factory function that creates atoms on-demand based on a parameter (like an ID). Think of it as a "vending machine for atoms" — give it a key, get back a dedicated atom for that item.

import { atomFamily } from 'jotai/utils';

// Create the family
const todoAtomFamily = atomFamily((id) => 
  atom({ id, text: '', completed: false })
);

// In components, get atoms by ID
function TodoItem({ todoId }) {
  const [todo, setTodo] = useAtom(todoAtomFamily(todoId));
  // Only THIS todo's changes trigger re-render
}

Why This Matters

When you call todoAtomFamily(5), Jotai creates (or retrieves) an atom specifically for todo #5. Components subscribed to todoAtomFamily(5) only re-render when that specific todo changes. This is surgical precision compared to a monolithic atom where everything re-renders together.

Typical Use Cases

  • Lists with IDs: Todos, users, posts — anything with unique identifiers
  • Form fields: Create an atom per form field name
  • Dynamic routes: Per-page or per-entity state
  • Real-time data: Per-chat-room or per-notification state

The family handles caching automatically — calling todoAtomFamily(5) twice returns the same atom instance.

Key Takeaway: Atom families let you manage dynamic collections with granular reactivity — each item gets its own atom, so updates stay isolated and performance scales with your data.