Recipe Book0.6.0

4.15React reference

Hooks

Reference for useRecipe, useRecipeState, and useFormatIngredient, which give your own components the state and formatting that parts use.

§ 4.1512 min readView as Markdown

Three hooks give your own components the state and formatting that parts use. useRecipe() reads the state of the nearest <Recipe.Root>, and useFormatIngredient() formats its ingredients as text. useRecipeState() holds the state itself, without a Root. The Checklist page has two more, for a checklist’s ticks: useChecklist() reads those of the nearest <Recipe.Checklist>, and useChecklistState() holds them without one. A component that calls any of them needs 'use client'.

Whole numbers from 1 to 4,000,000

const { servings, scale, system, canConvert, ingredients } =
  Recipe.useRecipe()
const item = ingredients[0].items[0]
const format = Recipe.useFormatIngredient()
servings
4
scale
1
system
'us'
canConvert
true
item.quantity
{ amount: 1.5, unit: 'cup' }
format(item).text
'1 ½ cups all-purpose flour'

useRecipe

TypeScript
function useRecipe(): RecipeState

Returns the state of the nearest <Recipe.Root>: the recipe, its servings and measurement system, and the functions that change them.

TSX
'use client'

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

export function SystemSwitch() {
  const { system, setSystem, canConvert } = Recipe.useRecipe()
  if (!canConvert) return null

  return (
    <button onClick={() => setSystem(system === 'us' ? 'metric' : 'us')}>
      {system === 'us' ? 'Show metric' : 'Show US'}
    </button>
  )
}

Inside a Root for the sample recipe, which is written in US units, SystemSwitch renders:

HTML
<button>Show metric</button>

A click changes it to <button>Show US</button>. For a recipe whose only quantity is a count, such as 2 slices of bread, it renders nothing.

Returns

RecipeState.

Errors

Throws missing_parent when a component outside <Recipe.Root> calls it:

Text
RecipeBookError: useRecipe() must be called inside <Recipe.Root>. To use recipe state without a Root, call useRecipeState().
See https://recipe-book.siraj.page/errors/missing_parent/

useFormatIngredient

TypeScript
function useFormatIngredient(): (
  item: RecipeIngredientItem,
) => RecipeFormattedIngredient

Returns a function that formats an ingredient as <Recipe.Ingredient> does, with the locale and labels of the nearest <Recipe.Root>.

TSX
'use client'

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

export function CopyIngredients() {
  const { ingredients } = Recipe.useRecipe()
  const format = Recipe.useFormatIngredient()
  const lines = ingredients
    .flatMap((section) => section.items)
    .map((item) => {
      const formatted = format(item)
      return formatted.optionalLabel
        ? `${formatted.text} ${formatted.optionalLabel}`
        : formatted.text
    })

  return (
    <button onClick={() => navigator.clipboard.writeText(lines.join('\n'))}>
      Copy ingredients
    </button>
  )
}

Inside a Root for the sample recipe, a click on Copy ingredients copies:

Text
1 ½ cups all-purpose flour
2 tbsp sugar
2 tsp baking powder
1 ¼ cups buttermilk
2 eggs
3 tbsp butter, melted
maple syrup, to serve

Call it when you need text instead of elements: to copy the ingredients, as here, to put one in an attribute, or to render somewhere other than the DOM. To show ingredients on the page, use the ingredient parts, which add the data-recipe-* attributes and follow the dash of a quantity range, as in “2–3 tbsp”, with the to label in text that’s hidden on screen, so in Chrome and Firefox the label takes the dash’s place. The function’s text never includes the optional label: add optionalLabel yourself, as CopyIngredients does.

Returns

A function that takes a RecipeIngredientItem and returns a RecipeFormattedIngredient. useFormatIngredient() returns the same function until Root’s locale, labels.optional, or measurement system changes, so you can list it in a hook’s dependencies. Once a Root or provider sets a pack, it also returns a new function whenever the nearest Root or provider that sets one gets a new labels object, so define labels at module scope.

Errors

Throws missing_parent when a component outside <Recipe.Root> calls it, even one inside a <Recipe.Provider>:

Text
RecipeBookError: useFormatIngredient() must be called inside <Recipe.Root>. To format ingredients without a Root, call formatIngredient() from @recipe-book/react/core.
See https://recipe-book.siraj.page/errors/missing_parent/

The function it returns throws invalid_argument when the item isn’t { ingredient, quantity? }, such as null, when Root’s locale isn’t a language tag that Intl accepts, such as 'en_US', or when the item’s quantity, or the size it shows after a count unit, has an amount that formatQuantity rejects, such as 0 or a range whose min is above its max, and unknown_unit when its unit isn’t a unit ID, unless it throws invalid_argument first, as it does for an amount of 0, or for an item from Root, 1e308 scaled past the largest number. A reversed size range doesn’t throw, though, where the count is a range and the size shows one figure for each item, as 200–201 cans whose only size is { min: 101, max: 100 } oz show “½ oz each” in 'us'. In 'metric', 14 g is more than 2% off 101 oz split 200 ways, so it switches to the total and throws because the total’s range is still reversed. It also throws invalid_argument, with a message that starts formatIngredient:, when the item’s ingredient has a name, plural, or note that isn’t a string, such as null.

In a runtime without Intl, the function that useFormatIngredient() returns doesn’t throw for any locale string, even 'en_US', and writes the numbers in English.

useRecipeState

TypeScript
function useRecipeState(options: RecipeStateOptions): RecipeState

Holds a recipe’s state without a <Recipe.Root>. <Recipe.Root> is built on it, so the state works the same way: controlled or uncontrolled, within the same servings window, with the same development warnings.

TSX
'use client'

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

export function ServingsSummary({ recipe }: { recipe: ParsedRecipe }) {
  const { scaledServings, scale } = Recipe.useRecipeState({
    recipe,
    defaultServings: 8,
  })

  return (
    scaledServings && (
      <p>{`Serves ${formatServings(scaledServings)}, scaled ×${scale}`}</p>
    )
  )
}

For the sample recipe, which has 4 servings, ServingsSummary renders:

HTML
<p>Serves 8, scaled ×2</p>

For a recipe with a yield but no servings, scaledServings is undefined, so ServingsSummary renders nothing. defaultServings then counts in the yield’s unit, and scaledYield holds the yield, which formatYield writes as “8 cookies”.

Parts and useRecipe() can’t read this state, because it isn’t in a Root. To share it with other components, pass it to them as props.

Name Type Default Description
options RecipeStateOptions Required The recipe and its state.

Returns

RecipeState.

Errors

In development, throws invalid_argument when recipe doesn’t have a parsed recipe’s shape, which it checks as <Recipe.Root> does:

Text
RecipeBookError: useRecipeState(): 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 throws the same error when options has no recipe, such as for useRecipeState() or useRecipeState(recipe). For useRecipeState(), the message says to call useRecipe() to read the state of the nearest Root; otherwise it says to pass { recipe }.

Types

@recipe-book/react exports each of these types. Name them through the namespace, such as Recipe.RecipeState:

TypeScript
import type * as Recipe from '@recipe-book/react'

export function isScaled(state: Recipe.RecipeState): boolean {
  return state.scale !== 1
}

RecipeState

TypeScript
type RecipeState = {
  recipe: Recipe
  servings: number
  setServings: (servings: number) => void
  scale: number
  scaledServings?: Servings | undefined
  scaledYield?: Yield | undefined
  system: System
  setSystem: (system: System) => void
  canConvert: boolean
  ingredients: readonly RecipeSection<RecipeIngredientItem>[]
  steps: readonly RecipeSection<RecipeStepItem>[]
  idPrefix: string
}

What useRecipe() and useRecipeState() return.

Name Type Description
recipe Recipe The parsed recipe.
servings number The number of servings shown, counted from the recipe’s scaling base. For a recipe with a yield but no servings, it counts in the yield’s unit.
setServings (servings: number) => void Calls onServingsChange, and changes the number of servings unless servings are controlled. Ignores any number outside the servings window, and the current number unless a controlled servings is outside the window, or another number passed to it inside a transition is pending and, if servings are controlled, <Recipe.Root>, or the component that calls useRecipeState, has rendered since. A number pending only in the parent’s own transition doesn’t count.
scale number servings divided by the recipe’s scaling base.
scaledServings Servings | undefined The recipe’s servings at scale, or undefined for a recipe without servings. At a scale within 1e-9 of 1, the servings as written, so a range such as 6–8 stays one. At any other scale, { amount: servings } when the servings are the scaling base, plus a max that isn’t greater than the amount, scaled, which only a recipe you build can have. <Recipe.ServingsText> shows them.
scaledYield Yield | undefined The recipe’s yield at scale, or undefined for a recipe without one. At a scale within 1e-9 of 1, the yield as written. When the servings are the scaling base, both ends of a range scale, so 12–16 rolls for 4 servings are 24–32 rolls at 8. Otherwise, as for a recipe with only a yield, any other scale gives { amount: servings, unit, plural }. Either way, when the yield’s own amount is a finite number greater than 0, a max that isn’t greater than it, which only a recipe you build can have, is kept and scaled. When it isn’t, a max that isn’t greater than it is dropped at a scale more than 1e-9 from 1, which is every max when amount is NaN or Infinity. <Recipe.YieldText> shows it.
system System The measurement system shown.
setSystem (system: System) => void Calls onSystemChange, and changes the measurement system unless it’s controlled. Ignores anything but 'metric' and 'us', and the current system unless a controlled system is neither, or another system passed to it inside a transition is pending and, if the system is controlled, <Recipe.Root>, or the component that calls useRecipeState, has rendered since. A system pending only in the parent’s own transition doesn’t count.
canConvert boolean true when an ingredient’s quantity, or any equivalent of a quantity in a count unit, such as the size of a can, has a unit that belongs to only one measurement system or, in a Root, a mounted <Recipe.StepText> or <Recipe.ConvertedStepText> shows a temperature, or a mounted <Recipe.ConvertedStepText> shows a quantity that one of the systems would convert. From useRecipeState(), it counts ingredients only. See Recipes that can’t convert.
ingredients readonly RecipeSection<RecipeIngredientItem>[] Each section’s ingredients at servings, in system, scaled but not formatted. US volume converted from metric, or scaled in cups or spoons, can land on a cup or spoon measure unless exact is set. In 'us', quarts, pints, gallons, and fluid ounces only scale, so 2 quarts for 4 servings is 2.74 quarts for 5.48, and at a scale within 1e-9 of 1, an amount in its own system and unit stays as written, so 1.3 cups stays 1.3 cups, but a range whose min equals its max gives its min. A range whose min is greater than its max, or whose max is missing, null, or NaN, which only a recipe you build can have, is kept and scaled. <Recipe.Ingredient> and the function that useFormatIngredient() returns throw invalid_argument for it at every scale. Where scaling or converting makes the range’s ends equal, it gives one amount instead. At twice the servings in metric, 1 cup of milk has the quantity { amount: 473.176473, unit: 'ml' }.
steps readonly RecipeSection<RecipeStepItem>[] The recipe’s steps in their sections.
idPrefix string Comes before each step’s id in the id that <Recipe.Step> renders, so `#${idPrefix}${step.id}` links to a step. The Root’s idPrefix, or the recipe’s id and a hyphen, which is what useRecipeState() gives.

setSystem stays the same function while the component holding the state is mounted, and setServings does too until the recipe’s scaling base changes, so passing one to a memo component doesn’t make it render again when the servings or system change. Don’t change the state or anything in it, such as recipe, which is the object you passed.

RecipeStateOptions

TypeScript
type RecipeStateOptions = {
  recipe: Recipe
  servings?: number | undefined
  defaultServings?: number | undefined
  onServingsChange?: ((servings: number) => void) | undefined
  system?: System | undefined
  defaultSystem?: System | undefined
  onSystemChange?: ((system: System) => void) | undefined
  exact?: boolean | undefined
}

What useRecipeState() takes. The state props of <Recipe.Root> are the same.

Name Type Description
recipe Recipe A parsed recipe: result.data from parseRecipe.
servings number | undefined The number of servings to show. Passing it makes servings controlled.
defaultServings number | undefined The number of servings to start with when servings are uncontrolled. Defaults to the recipe’s scaling base.
onServingsChange ((servings: number) => void) | undefined Called with the new number of servings each time setServings accepts one, whether or not servings are controlled.
system System | undefined The measurement system to show. Passing it makes the system controlled.
defaultSystem System | undefined The measurement system to start with when the system is uncontrolled. Defaults to the nearest provider’s, then the recipe’s, then 'metric'.
onSystemChange ((system: System) => void) | undefined Called with the new system each time setSystem accepts one, whether or not the system is controlled.
exact boolean | undefined Pass true to keep amounts exact when they’re shown in another system or rebalanced, so 150 mL in 'us' is 10.1442… tbsp, which formatIngredient and the parts show as 10 ⅛ tbsp, rather than 10 tbsp. The unit is still the one a cook measures with.

RecipeFormattedIngredient

TypeScript
type RecipeFormattedIngredient = FormattedIngredient & {
  quantityParts: readonly QuantityPart[]
  optionalLabel?: string | undefined
}

What the function from useFormatIngredient() returns: an ingredient in the pieces that <Recipe.Ingredient> renders. The first five fields are core’s FormattedIngredient.

Name Type Description
quantity string | undefined The quantity, as formatQuantity formats it with Root’s locale and labels. Absent when the ingredient has none.
size string | undefined For a can, a package, or another count unit with a mass or volume equivalent, its size as text shows it in parentheses, such as 15 oz each for 2 cans, as formatIngredient describes. Absent otherwise. quantity and quantityParts leave it out.
name string The name, or the plural after a bare count that takes it, as in 2 eggs. A plural that’s empty or only whitespace reads as none.
note string | undefined The note. Absent when the ingredient has none.
text string The quantity, any size in parentheses, the name, and the note after a comma, joined as formatIngredient joins them. It never includes optionalLabel.
quantityParts readonly QuantityPart[] The quantity in pieces, from formatQuantityToParts. Empty when the ingredient has no quantity.
optionalLabel string | undefined The optional label. Absent when the ingredient isn’t optional.

For an ingredient written as { name: 'lemon', plural: 'lemons', quantity: '1–2', note: 'zested', optional: true }, the function returns:

TypeScript
import type * as Recipe from '@recipe-book/react'

export const lemon: Recipe.RecipeFormattedIngredient = {
  quantity: '1–2',
  name: 'lemons',
  note: 'zested',
  text: '1–2\u00a0lemons, zested',
  quantityParts: [
    { type: 'amount', value: '1' },
    { type: 'rangeSeparator', value: '–' },
    { type: 'amount', value: '2' },
  ],
  optionalLabel: '(optional)',
}

RecipeStepItem

TypeScript
type RecipeStepItem = Step & { number: number }

A Step with its number. <Recipe.Step> takes one as item.

Name Type Description
number number The step’s position, counted from 1 across sections. For a recipe with one untitled step and a “Cook” section of two steps, the steps in “Cook” are numbers 2 and 3.

RecipeSection

TypeScript
type RecipeSection<T> = {
  id: string
  title?: string | undefined
  items: readonly T[]
}

A section of a recipe’s ingredients or steps.

Name Type Description
id string The section’s ID from the recipe.
title string | undefined The section’s title. Absent when it has none.
items readonly T[] The items in the section.
Contents