# atomFamily

Signature
`atomFamily<K, T>(defaultFactory?: (key: K) => T): AtomFamily<K, T>`

valdres
Create a keyed collection of atoms

Creates a family of atoms keyed by a parameter. Useful for collections of entities like users, todos, or items where each instance needs its own piece of state.

## Usage

```ts
import { atomFamily } from "valdres"

// Simple family with no default
const todoAtom = atomFamily()

store.set(todoAtom("abc-123"), { title: "Buy milk", done: false })
store.get(todoAtom("abc-123")) // { title: "Buy milk", done: false }
```

## With a default value factory

Pass a function that receives the key and returns the default value:

```ts
const userAtom = atomFamily(id => ({
    id,
    name: "",
    email: "",
}))

// The default is generated when first accessed
store.get(userAtom("user-1")) // { id: "user-1", name: "", email: "" }
```

## Subscribing to all keys

> **Tip**
>
>
> Unlike Jotai, you can subscribe to an entire family and get all active keys as an array. This is a first-class feature, not a workaround.

```ts
store.sub(todoAtom, keys => {
    console.log("Active todo keys:", keys)
})
```

## In React

```tsx
import { useValue } from "valdres-react"

function UserProfile({ userId }) {
    const user = useValue(userAtom(userId))
    return <div>{user.name}</div>
}
```

## See also

- [atom](https://valdres.dev/valdres/atom) — create a single atom
- [selectorFamily](https://valdres.dev/valdres/selectorFamily) — derive state from a family of atoms
