# Checklist

> Reference for <Recipe.Checklist>, <Recipe.IngredientCheckbox>, <Recipe.StepCheckbox>, useChecklist, and useChecklistState, which let readers check off ingredients and steps.

Source: https://recipe-book.siraj.page/reference/react/checklist/

Readers can check off ingredients as they gather them and steps as they finish them. [`<Recipe.Checklist>`](https://recipe-book.siraj.page/reference/react/checklist.md#checklist) holds which ones are ticked, and the [ingredient](https://recipe-book.siraj.page/reference/react/ingredients.md) and [step](https://recipe-book.siraj.page/reference/react/steps.md) lists inside it show a checkbox for each item. [`<Recipe.IngredientCheckbox>`](https://recipe-book.siraj.page/reference/react/checklist.md#ingredientcheckbox) and [`<Recipe.StepCheckbox>`](https://recipe-book.siraj.page/reference/react/checklist.md#stepcheckbox) place the checkbox in your own children, [`useChecklist()`](https://recipe-book.siraj.page/reference/react/checklist.md#usechecklist) reads and sets the ticks, and [`useChecklistState()`](https://recipe-book.siraj.page/reference/react/checklist.md#usecheckliststate) holds them without a Checklist.

## `Checklist`

```tsx
import { parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  servings: 4,
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups' },
    { name: 'egg', plural: 'eggs', quantity: 2 },
  ],
  steps: [
    'Whisk the dry ingredients in a large bowl.',
    'Cook ¼-cup portions, 2–3 minutes per side.',
  ],
})
if (!result.success) throw result.error
const recipe = result.data

export function Method() {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Checklist>
        <Recipe.Steps />
      </Recipe.Checklist>
    </Recipe.Root>
  )
}
```

`Method` renders this HTML, indented here for reading:

```html
<div data-recipe-steps="">
  <div data-recipe-step-section="">
    <ol start="1" data-recipe-step-list="">
      <li id="buttermilk-pancakes-step-1" data-recipe-step=""><label><input autoComplete="off" type="checkbox" data-recipe-step-checkbox=""/> <span data-recipe-step-text="">Whisk the dry ingredients in a large bowl.</span></label></li>
      <li id="buttermilk-pancakes-step-2" data-recipe-step=""><label><input autoComplete="off" type="checkbox" data-recipe-step-checkbox=""/> <span data-recipe-step-text="">Cook ¼-cup portions, <span data-recipe-duration="">2–⁠3 minutes</span> per side.</span></label></li>
    </ol>
  </div>
</div>
```

`<Recipe.Checklist>` renders no element of its own, and must be inside a [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md). Inside it, the default children of each [`<Recipe.Step>`](https://recipe-book.siraj.page/reference/react/steps.md#step) follow a [`<Recipe.StepCheckbox>`](https://recipe-book.siraj.page/reference/react/checklist.md#stepcheckbox) in a `<label>`, so a click on the step's text ticks the box too, and those of each [`<Recipe.Ingredient>`](https://recipe-book.siraj.page/reference/react/ingredients.md#ingredient) follow an [`<Recipe.IngredientCheckbox>`](https://recipe-book.siraj.page/reference/react/checklist.md#ingredientcheckbox). The lists render those items, so [`<Recipe.Steps>`](https://recipe-book.siraj.page/reference/react/steps.md#steps), [`<Recipe.StepList>`](https://recipe-book.siraj.page/reference/react/steps.md#steplist), [`<Recipe.Ingredients>`](https://recipe-book.siraj.page/reference/react/ingredients.md#ingredients), and [`<Recipe.IngredientList>`](https://recipe-book.siraj.page/reference/react/ingredients.md#ingredientlist) show checkboxes too, unless a list has [`checkboxes={false}`](https://recipe-book.siraj.page/reference/react/checklist.md#lists-without-checkboxes). A ticked item's `<li>` has `data-checked`. Outside a Checklist, the parts render as they do without one, with no checkboxes and no `data-checked`. A `<Recipe.Root>` inside a Checklist, for a recipe with another `id`, starts outside it, so its parts show checkboxes only in a Checklist of its own. One for a different recipe with the same `id` joins the Checklist, whatever its `idPrefix`: its boxes tick the outer recipe's items with the same IDs, and its items the outer recipe doesn't have can't be ticked.

An item with `asChild`, as in [Render your own element](https://recipe-book.siraj.page/reference/react/ingredients.md#render-your-own-element), puts those default children in a child that has none, so an empty `<label>` child renders a `<label>` inside a `<label>`, which HTML doesn't allow. Render an `<li>`, as that section says, and the default `<label>` goes inside it. A `<label>` child suits only an item outside a list, and then needs its own children, with an `IngredientCheckbox` or `StepCheckbox` among them.

The file needs no `'use client'`, because the parts are already [Client Components](https://recipe-book.siraj.page/reference/react/root.md#root). A file that passes a function, such as `onCheckedStepsChange`, needs it, as in [Controlled and uncontrolled](https://recipe-book.siraj.page/reference/react/checklist.md#controlled-and-uncontrolled).

Before React hydrates the page, each box is a plain checkbox, so a reader can tick or untick it while the page loads, and those changes pass to the Checklist once React hydrates the page. On React 18, while a Suspense boundary below the Checklist hasn't hydrated yet, such as one waiting for a lazy component's code, an item's `data-checked` follows such a change only once that boundary hydrates, though its box keeps the change and `onCheckedIngredientsChange` or `onCheckedStepsChange` is called at once. A box inside that boundary passes its change to the Checklist only once the boundary hydrates, on any React version. On React 18, ticking a box after hydration while a Suspense boundary inside the same Checklist still waits for code or streamed data makes React report error #421, throw away that boundary's server HTML, and show its fallback until the wait ends. Keep lazy or streamed content, such as React Router's `<Await>`, out of the Checklist on React 18 to avoid it.

When the ticks are [controlled](https://recipe-book.siraj.page/reference/react/checklist.md#controlled-and-uncontrolled) and `onCheckedIngredientsChange` or `onCheckedStepsChange` doesn't take a change, its box goes back to the parent's value. To keep ticks from one visit to the next, [remember them](https://recipe-book.siraj.page/reference/react/checklist.md#remember-the-ticks).

| Name                         | Type                                              | Description                                                                                                         |
| ---------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `checkedIngredients`         | `readonly string[] \| undefined`                  | The IDs of the ticked ingredients. Passing it makes them controlled.                                                |
| `defaultCheckedIngredients`  | `readonly string[] \| undefined`                  | The IDs to tick at first when the ingredients are uncontrolled. Defaults to `[]`.                                   |
| `onCheckedIngredientsChange` | `((ids: readonly string[]) => void) \| undefined` | Called with the ticked ingredients' IDs, in recipe order, each time they change, whether or not they're controlled. |
| `checkedSteps`               | `readonly string[] \| undefined`                  | The IDs of the ticked steps. Passing it makes them controlled.                                                      |
| `defaultCheckedSteps`        | `readonly string[] \| undefined`                  | The IDs to tick at first when the steps are uncontrolled. Defaults to `[]`.                                         |
| `onCheckedStepsChange`       | `((ids: readonly string[]) => void) \| undefined` | Called with the ticked steps' IDs, in recipe order, each time they change, whether or not they're controlled.       |
| `children`                   | `ReactNode \| undefined`                          | The parts and components that show or set the ticks.                                                                |

An ingredient's ID is the [`id`](https://recipe-book.siraj.page/reference/core/types.md#ingredient) the parsed recipe gives it, such as `'egg'`, and a step's is its [`id`](https://recipe-book.siraj.page/reference/core/types.md#step), such as `'step-1'`. Each [`RecipeIngredientItem`](https://recipe-book.siraj.page/reference/react/ingredients.md#recipeingredientitem) and [`RecipeStepItem`](https://recipe-book.siraj.page/reference/react/hooks.md#recipestepitem) has its `id`. The Checklist ignores IDs that aren't in the recipe. Uncontrolled ticks go back to their defaults when the recipe's [`id`](https://recipe-book.siraj.page/reference/core/types.md#recipe) changes, so when the Root gets another recipe, the ticks of the first recipe's `'step-1'` don't carry over to the second's. That reset doesn't call `onCheckedIngredientsChange` or `onCheckedStepsChange`.

### Lists without checkboxes

Pass `checkboxes={false}` to a list whose items are ticked some other way. Here, a button ticks the steps one at a time, and the ingredients keep their checkboxes:

```tsx {28}
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

function DoneButton() {
  const { steps } = Recipe.useRecipe()
  const { checkedSteps, setCheckedSteps } = Recipe.useChecklist()
  const next = steps
    .flatMap((section) => section.items)
    .find((step) => !checkedSteps.includes(step.id))

  return (
    <button
      aria-disabled={next ? undefined : true}
      onClick={() => next && setCheckedSteps([...checkedSteps, next.id])}
    >
      {next ? `Done with step ${next.number}` : 'All steps done'}
    </button>
  )
}

export function StepByStep({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Checklist>
        <Recipe.Ingredients />
        <Recipe.Steps checkboxes={false} />
        <DoneButton />
      </Recipe.Checklist>
    </Recipe.Root>
  )
}
```

For the recipe in the first example, `StepByStep` renders this HTML, with a no-break space (U+00A0) where you see a space inside a quantity, and after a count with no unit, as in "2 eggs":

```html {12-13}
<div data-recipe-ingredients="">
  <div data-recipe-ingredient-section="">
    <ul data-recipe-ingredient-list="">
      <li data-recipe-ingredient="" data-origin="authored"><label><input autoComplete="off" type="checkbox" data-recipe-ingredient-checkbox=""/> <span data-recipe-ingredient-quantity="">1 ½ cups</span> <span data-recipe-ingredient-name="">all-purpose flour</span></label></li>
      <li data-recipe-ingredient="" data-origin="authored"><label><input autoComplete="off" type="checkbox" data-recipe-ingredient-checkbox=""/> <span data-recipe-ingredient-quantity="">2</span> <span data-recipe-ingredient-name="">eggs</span></label></li>
    </ul>
  </div>
</div>
<div data-recipe-steps="">
  <div data-recipe-step-section="">
    <ol start="1" data-recipe-step-list="">
      <li id="buttermilk-pancakes-step-1" data-recipe-step=""><span data-recipe-step-text="">Whisk the dry ingredients in a large bowl.</span></li>
      <li id="buttermilk-pancakes-step-2" data-recipe-step=""><span data-recipe-step-text="">Cook ¼-cup portions, <span data-recipe-duration="">2–⁠3 minutes</span> per side.</span></li>
    </ol>
  </div>
</div>
<button>Done with step 1</button>
```

A click on **Done with step 1** ticks the first step, and the button changes to **Done with step 2**. After the last step, it reads **All steps done** and has `aria-disabled` rather than `disabled`, so it keeps the keyboard focus. Style the ticked steps with `data-checked`:

```css
[data-recipe-step][data-checked] {
  text-decoration: line-through;
}
```

A strikethrough keeps the text at full contrast, where `opacity: 0.5` fades black text on white to a contrast ratio of about 4 to 1, under the 4.5 to 1 that WCAG 2.2's [contrast minimum](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) asks of body text. A list without checkboxes shows its ticks only through `data-checked`, which screen readers don't announce, so say the state in text, as the button does.

A list inside another follows its `checkboxes` unless it sets its own, so each `<Recipe.StepList>` that `<Recipe.Steps checkboxes={false} />` renders has no checkboxes either. Outside a Checklist, `checkboxes` does nothing.

## Controlled and uncontrolled

The ingredients' ticks and the steps' ticks are each uncontrolled unless you pass `checkedIngredients` or `checkedSteps`, as the Root's [servings and system](https://recipe-book.siraj.page/reference/react/root.md#controlled-and-uncontrolled-state) are, with the same [development warnings](https://recipe-book.siraj.page/errors.md#warning-read-only), as when `checkedSteps` is passed without `onCheckedStepsChange`. Control them to read them outside the Root, as this heading does:

```tsx {9,16-17}
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useState } from 'react'

export function Method({ recipe }: { recipe: ParsedRecipe }) {
  const count = recipe.steps.reduce((n, section) => n + section.items.length, 0)
  const [checked, setChecked] = useState<readonly string[]>([])

  return (
    <>
      <h2>{`Method: ${checked.length} of ${count} done`}</h2>
      <Recipe.Root recipe={recipe}>
        <Recipe.Checklist
          checkedSteps={checked}
          onCheckedStepsChange={setChecked}
        >
          <Recipe.Steps />
        </Recipe.Checklist>
      </Recipe.Root>
    </>
  )
}
```

For the recipe in the first example, the heading reads `Method: 0 of 2 done`, and ticking a step changes it to `Method: 1 of 2 done`. Inside the Checklist, [`useChecklist()`](https://recipe-book.siraj.page/reference/react/checklist.md#usechecklist) reads the same ticks without controlling them.

Pass your state itself as `checkedSteps` or `checkedIngredients`, not a value from `useDeferredValue`. A deferred list lags behind the ticks, and the Checklist takes it as the parent's answer, so a tick made before it catches up builds on the older list and loses the tick before it. To keep a slow part of the page from holding up the boxes, pass the deferred value to that part instead.

Update your state urgently in `onCheckedStepsChange` or `onCheckedIngredientsChange`, not in a transition. Until a transition commits, the box goes back to the parent's value. On React 19, to save the ticks in a transition, such as with a Server Action, pass the value from `useOptimistic` as `checkedSteps` or `checkedIngredients`, and set it first in the transition: each tick shows at once, and once the transition ends, the boxes show your state again, so a save that fails goes back to the ticks you last saved.

### Remember the ticks

A Checklist doesn't remember the ticks, so each page load starts with the same ones. To remember them, save them in `onCheckedStepsChange`, and restore them with `setCheckedSteps` after the page loads. This example keeps them in `localStorage`, under the recipe's `id`, so it assumes no other recipe on the site has the same `id`. Two recipes named "Pancakes" without `id`s of their own, for example, have the same one, and restore each other's ticks:

```tsx {10-13,21-23,25}
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { startTransition, useEffect } from 'react'

function RestoreTicks() {
  const { recipe } = Recipe.useRecipe()
  const { setCheckedSteps } = Recipe.useChecklist()
  useEffect(() => {
    const saved = localStorage.getItem(`ticks-${recipe.id}`)
    if (saved) startTransition(() => setCheckedSteps(JSON.parse(saved)))
  }, [recipe.id, setCheckedSteps])
  return null
}

export function Method({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Checklist
        onCheckedStepsChange={(ids) =>
          localStorage.setItem(`ticks-${recipe.id}`, JSON.stringify(ids))
        }
      >
        <RestoreTicks />
        <Recipe.Steps />
      </Recipe.Checklist>
    </Recipe.Root>
  )
}
```

The server can't read `localStorage`, so the page renders with no steps ticked, and ticks the saved ones once React hydrates it. A saved value that isn't an array of strings logs a [development warning](https://recipe-book.siraj.page/errors.md#warning-invalid-set-checked), and the steps stay as they were. One that isn't JSON makes `JSON.parse` throw: React 19 reports the error, and the steps stay as they were, but React 18 unmounts the page on each load until the value is cleared.

The restore is a transition so that, on React 18, a Suspense boundary inside the Checklist that hasn't hydrated yet, such as one waiting for a lazy component's code, hydrates first. Until it does, none of the saved ticks show, not only the ones in that boundary. An urgent update makes React 18 report error #421, throw away that boundary's server HTML, and show its fallback until the code loads.

With controlled ticks, restore through `setCheckedSteps` or `setCheckedIngredients` from `useChecklist()`, as `RestoreTicks` does, not by setting your own state in a transition. A tick made before your transition commits builds on the ticks shown, so the restored ones are lost.

In an app that renders only in the browser, read the saved IDs before the first render and pass them as [`defaultCheckedSteps`](https://recipe-book.siraj.page/reference/react/checklist.md#checklist) instead of using `RestoreTicks`, so the steps are ticked from the first render.

A step without an `id` or a `name` gets its ID from its position, such as `'step-2'`, with `-2` and so on added as for other repeated IDs, so a saved tick moves to another step when a step is added or removed above it. To keep each tick on its step, give the steps IDs, or drop the saved ticks when the steps change.

## `IngredientCheckbox`

```tsx {14}
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function ShoppingList({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Checklist>
        <Recipe.IngredientList>
          {(item) => (
            <Recipe.Ingredient item={item}>
              <label>
                <Recipe.IngredientCheckbox /> <Recipe.IngredientName />
              </label>
            </Recipe.Ingredient>
          )}
        </Recipe.IngredientList>
      </Recipe.Checklist>
    </Recipe.Root>
  )
}
```

For the recipe in the first example, `ShoppingList` renders:

```html
<ul data-recipe-ingredient-list="">
  <li data-recipe-ingredient="" data-origin="authored"><label><input autoComplete="off" type="checkbox" data-recipe-ingredient-checkbox=""/> <span data-recipe-ingredient-name="">all-purpose flour</span></label></li>
  <li data-recipe-ingredient="" data-origin="authored"><label><input autoComplete="off" type="checkbox" data-recipe-ingredient-checkbox=""/> <span data-recipe-ingredient-name="">eggs</span></label></li>
</ul>
```

`<Recipe.IngredientCheckbox>` renders an `<input type="checkbox">` that ticks the nearest [`<Recipe.Ingredient>`](https://recipe-book.siraj.page/reference/react/ingredients.md#ingredient) in the nearest `<Recipe.Checklist>`. Custom children replace the ingredient's default children, checkbox included, so place one yourself. Put it in a `<label>` with the text it ticks, so the box has an accessible name and a click on the text ticks it.

| Name           | Type                                                            | Description                                                                                                                                                                                                                                           |
| -------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `autoComplete` | `string \| undefined`                                           | The input's `autocomplete` attribute. Defaults to `'off'`, so when going back reloads the page, Chrome, Firefox, and Safari don't restore the earlier visit's tick. `null` (from JavaScript, or without `strictNullChecks`) leaves the attribute out. |
| `onChange`     | `((event: ChangeEvent<HTMLInputElement>) => void) \| undefined` | Runs before the box ticks or unticks the ingredient. Call `event.preventDefault()` in it, or in an `onClick` on the box or around it, to keep the ingredient as it was.                                                                               |

Any other `<input>` prop, such as `className` or `aria-label`, passes to the `<input>`, and a `ref` reaches it. Style it with `className`, or select the `data-recipe-ingredient-checkbox` attribute, which it always sets. The part sets the type and whether the box is ticked, so it doesn't take `type`, `checked`, `defaultChecked`, `children`, or `dangerouslySetInnerHTML`.

## `StepCheckbox`

```tsx {14}
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function Method({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Checklist>
        <Recipe.StepList>
          {(step) => (
            <Recipe.Step item={step}>
              <label>
                <Recipe.StepText /> <Recipe.StepCheckbox />
              </label>
            </Recipe.Step>
          )}
        </Recipe.StepList>
      </Recipe.Checklist>
    </Recipe.Root>
  )
}
```

For the recipe in the first example, `Method` renders:

```html
<ol start="1" data-recipe-step-list="">
  <li id="buttermilk-pancakes-step-1" data-recipe-step=""><label><span data-recipe-step-text="">Whisk the dry ingredients in a large bowl.</span> <input autoComplete="off" type="checkbox" data-recipe-step-checkbox=""/></label></li>
  <li id="buttermilk-pancakes-step-2" data-recipe-step=""><label><span data-recipe-step-text="">Cook ¼-cup portions, <span data-recipe-duration="">2–⁠3 minutes</span> per side.</span> <input autoComplete="off" type="checkbox" data-recipe-step-checkbox=""/></label></li>
</ol>
```

`<Recipe.StepCheckbox>` renders an `<input type="checkbox">` that ticks the nearest [`<Recipe.Step>`](https://recipe-book.siraj.page/reference/react/steps.md#step) in the nearest `<Recipe.Checklist>`. As with [`<Recipe.IngredientCheckbox>`](https://recipe-book.siraj.page/reference/react/checklist.md#ingredientcheckbox), custom children replace the step's checkbox, so place one in a `<label>` with the text it ticks. It takes the same props, and sets `data-recipe-step-checkbox` instead. [Render your own steps](https://recipe-book.siraj.page/reference/react/steps.md#render-your-own-steps) puts it in a label of its own, before the step's text.

## In a form

A form sends a ticked checkbox only when the box has a `name`. The boxes that the lists show by default have none, so a form around them sends no ticks. To send the ticks, place the boxes yourself, as in the [`IngredientCheckbox`](https://recipe-book.siraj.page/reference/react/checklist.md#ingredientcheckbox) and [`StepCheckbox`](https://recipe-book.siraj.page/reference/react/checklist.md#stepcheckbox) examples, and give each one a `name` and its item's ID as its `value`, such as `<Recipe.IngredientCheckbox name="have" value={item.id} />`. For the recipe in the first example, with both ingredients ticked, `formData.getAll('have')` returns `['all-purpose-flour', 'egg']`.

A form reset, such as a reset button's or the one React 19 runs after a form's `action`, leaves each box as the Checklist has it, so the ticks stay. To clear them, call `setCheckedIngredients([])` or `setCheckedSteps([])` from [`useChecklist()`](https://recipe-book.siraj.page/reference/react/checklist.md#usechecklist).

## `useChecklist`

```ts
function useChecklist(): RecipeChecklistState
```

Returns the ticks of the nearest `<Recipe.Checklist>` and the functions that set them.

```tsx {8,22}
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

function Progress() {
  const { steps } = Recipe.useRecipe()
  const { checkedSteps, setCheckedSteps } = Recipe.useChecklist()
  const count = steps.reduce((n, section) => n + section.items.length, 0)

  return (
    <p>
      {`${checkedSteps.length} of ${count} steps done `}
      <button onClick={() => setCheckedSteps([])}>Clear</button>
    </p>
  )
}

export function Method({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Checklist defaultCheckedSteps={['step-1']}>
        <Progress />
        <Recipe.StepList />
      </Recipe.Checklist>
    </Recipe.Root>
  )
}
```

For the recipe in the first example, `Method` starts with the first step ticked:

```html {3}
<p>1 of 2 steps done <button>Clear</button></p>
<ol start="1" data-recipe-step-list="">
  <li id="buttermilk-pancakes-step-1" data-recipe-step="" data-checked=""><label><input autoComplete="off" type="checkbox" data-recipe-step-checkbox="" checked=""/> <span data-recipe-step-text="">Whisk the dry ingredients in a large bowl.</span></label></li>
  <li id="buttermilk-pancakes-step-2" data-recipe-step=""><label><input autoComplete="off" type="checkbox" data-recipe-step-checkbox=""/> <span data-recipe-step-text="">Cook ¼-cup portions, <span data-recipe-duration="">2–⁠3 minutes</span> per side.</span></label></li>
</ol>
```

A click on **Clear** unticks it, and the paragraph reads `0 of 2 steps done`.

### Returns

[`RecipeChecklistState`](https://recipe-book.siraj.page/reference/react/checklist.md#recipecheckliststate).

### Errors

Throws [`missing_parent`](https://recipe-book.siraj.page/errors/missing_parent.md) when a component outside `<Recipe.Checklist>` calls it, even one inside a Root, or inside a Root for a recipe with another `id` that's inside another Root's Checklist:

```txt
RecipeBookError: useChecklist() must be called inside <Recipe.Checklist>. To keep ticks without a Checklist, call useChecklistState().
See https://recipe-book.siraj.page/errors/missing_parent/
```

## `useChecklistState`

```ts
function useChecklistState(
  options: RecipeChecklistStateOptions,
): RecipeChecklistState
```

Holds a recipe's ticks without a `<Recipe.Checklist>`. `<Recipe.Checklist>` is built on it, so the ticks work the same way: controlled or uncontrolled, in recipe order, and back to their defaults when the recipe's `id` changes. Use it for a checklist in your own markup, without the ingredient or step parts:

```tsx
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function StepChecklist({ recipe }: { recipe: ParsedRecipe }) {
  const { checkedSteps, setCheckedSteps } = Recipe.useChecklistState({
    recipe,
  })
  const steps = recipe.steps.flatMap((section) => section.items)

  return (
    <ul>
      {steps.map((step) => (
        <li key={step.id}>
          <label>
            <input
              type="checkbox"
              checked={checkedSteps.includes(step.id)}
              onChange={(event) =>
                setCheckedSteps(
                  event.currentTarget.checked
                    ? [...checkedSteps, step.id]
                    : checkedSteps.filter((id) => id !== step.id),
                )
              }
            />{' '}
            <span>{step.text}</span>
          </label>
        </li>
      ))}
    </ul>
  )
}
```

For the recipe in the first example, `StepChecklist` renders:

```html
<ul>
  <li><label><input type="checkbox"/> <span>Whisk the dry ingredients in a large bowl.</span></label></li>
  <li><label><input type="checkbox"/> <span>Cook ¼-cup portions, 2–3 minutes per side.</span></label></li>
</ul>
```

The checkbox parts and `useChecklist()` can't read this state, because it isn't in a Checklist. Unlike the checkbox parts, these boxes don't pass a tick made before React hydrates the page to the state: the box stays ticked, but `checkedSteps` doesn't include it.

| Name      | Type                                                                                                                     | Default  | Description               |
| --------- | ------------------------------------------------------------------------------------------------------------------------ | -------- | ------------------------- |
| `options` | [`RecipeChecklistStateOptions`](https://recipe-book.siraj.page/reference/react/checklist.md#recipecheckliststateoptions) | Required | The recipe and its ticks. |

### Returns

[`RecipeChecklistState`](https://recipe-book.siraj.page/reference/react/checklist.md#recipecheckliststate).

### Errors

In development, throws [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) when `recipe` doesn't have a parsed recipe's shape, which it checks as [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md#parse-on-the-server) does:

```txt
RecipeBookError: useChecklistState(): recipe must be a parsed recipe, received an object that parseRecipe hasn't normalized. Call parseRecipe() from @recipe-book/react/core and pass result.data.
See https://recipe-book.siraj.page/errors/invalid_argument/
```

In development, it also throws `invalid_argument` when `options` has no `recipe`, such as for `useChecklistState()` or `useChecklistState(recipe)`, with a message that starts `useChecklistState(): expected options such as { recipe }`. For `useChecklistState()`, the message goes on to say to call [`useChecklist()`](https://recipe-book.siraj.page/reference/react/checklist.md#usechecklist) to read the ticks of the nearest Checklist; otherwise it says to pass `{ recipe }`.

## Errors

Each part throws [`missing_parent`](https://recipe-book.siraj.page/errors/missing_parent.md) when it isn't inside its parent. `<Recipe.Checklist>` must be inside `<Recipe.Root>`:

```txt
RecipeBookError: <Recipe.Checklist> must be rendered inside <Recipe.Root>.
See https://recipe-book.siraj.page/errors/missing_parent/
```

`<Recipe.StepCheckbox>` must be inside a `<Recipe.Step>`, and `<Recipe.IngredientCheckbox>` inside a `<Recipe.Ingredient>`:

```txt
RecipeBookError: <Recipe.StepCheckbox> must be rendered inside <Recipe.Step>.
See https://recipe-book.siraj.page/errors/missing_parent/
```

Each must be inside a `<Recipe.Checklist>` too. A Root inside a Checklist, for a recipe with another `id`, [starts outside it](https://recipe-book.siraj.page/reference/react/checklist.md#checklist), so in that Root, each needs a Checklist of its own:

```txt
RecipeBookError: <Recipe.StepCheckbox> must be rendered inside <Recipe.Checklist>.
See https://recipe-book.siraj.page/errors/missing_parent/
```

A value for `checkedIngredients` or `checkedSteps` that isn't an array of strings ticks nothing and logs a [development warning](https://recipe-book.siraj.page/errors.md#warning-invalid-checked). So does one for `defaultCheckedIngredients` or `defaultCheckedSteps`, with [its own warning](https://recipe-book.siraj.page/errors.md#warning-invalid-default-checked). A setter that gets one ignores it, and logs a [warning](https://recipe-book.siraj.page/errors.md#warning-invalid-set-checked) in development.

## Types

`@recipe-book/react` exports each part's props type: `RecipeChecklistProps`, `RecipeIngredientCheckboxProps`, and `RecipeStepCheckboxProps`. Use them to type a component that wraps a part:

```tsx
import * as Recipe from '@recipe-book/react'

export function Done(props: Recipe.RecipeStepCheckboxProps) {
  return <Recipe.StepCheckbox className="done" {...props} />
}
```

### `RecipeChecklistState`

```ts
type RecipeChecklistState = {
  checkedIngredients: readonly string[]
  setCheckedIngredients: (ids: readonly string[]) => void
  checkedSteps: readonly string[]
  setCheckedSteps: (ids: readonly string[]) => void
}
```

What `useChecklist()` and `useChecklistState()` return.

| Name                    | Type                               | Description                                                                                                                                                                                                                  |
| ----------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `checkedIngredients`    | `readonly string[]`                | The IDs of the ticked ingredients, in recipe order.                                                                                                                                                                          |
| `setCheckedIngredients` | `(ids: readonly string[]) => void` | Calls `onCheckedIngredientsChange` with the IDs in `ids` that are in the recipe, in recipe order, and ticks those ingredients and no others unless they're controlled. Does nothing when that leaves the ticks as they were. |
| `checkedSteps`          | `readonly string[]`                | The IDs of the ticked steps, in recipe order.                                                                                                                                                                                |
| `setCheckedSteps`       | `(ids: readonly string[]) => void` | Calls `onCheckedStepsChange` with the IDs in `ids` that are in the recipe, in recipe order, and ticks those steps and no others unless they're controlled. Does nothing when that leaves the ticks as they were.             |

### `RecipeChecklistStateOptions`

```ts
type RecipeChecklistStateOptions = {
  recipe: Recipe
  checkedIngredients?: readonly string[] | undefined
  defaultCheckedIngredients?: readonly string[] | undefined
  onCheckedIngredientsChange?: ((ids: readonly string[]) => void) | undefined
  checkedSteps?: readonly string[] | undefined
  defaultCheckedSteps?: readonly string[] | undefined
  onCheckedStepsChange?: ((ids: readonly string[]) => void) | undefined
}
```

What `useChecklistState()` takes: `recipe`, a parsed recipe, as `result.data` from [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe), and the ticks, as the [props of `<Recipe.Checklist>`](https://recipe-book.siraj.page/reference/react/checklist.md#checklist) describe them. A Checklist reads `recipe` from its Root, so it doesn't take it.

## Named imports

To import these parts by name, import each one without the `Recipe.`: `Checklist`, `IngredientCheckbox`, and `StepCheckbox`. If a name clashes with one of yours, alias it, as in `import { Checklist as RecipeChecklist } from '@recipe-book/react'`.
