4.1React reference
Root
Reference for <Recipe.Root>, which holds a recipe's servings and measurement system for the parts and hooks inside it.
<Recipe.Root> takes a parsed recipe and holds its state: the number of servings and the measurement system. Every part and every useRecipe() call inside it reads that state. It renders no element of its own, so style the parts inside it, as Style a recipe shows.
Buttermilk pancakes
- Prep
- 10 min
- Cook
- 15 min
Whole numbers from 1 to 4,000,000
Ingredients
- 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
Steps
- Whisk the dry ingredients in a large bowl.
- Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.
- Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.
Root
'use client'
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
function ScaleNote() {
const { scale } = Recipe.useRecipe()
return <p>{`Scaled ×${scale}`}</p>
}
export function RecipeCard({ recipe }: { recipe: ParsedRecipe }) {
return (
<Recipe.Root recipe={recipe} defaultServings={8}>
<Recipe.Image />
<Recipe.ServingsText />
<Recipe.YieldText />
<ScaleNote />
</Recipe.Root>
)
}For the sample recipe, which has 4 servings, RecipeCard renders:
<img src="/pancakes.svg" alt="Buttermilk pancakes" data-recipe-image=""/><span data-recipe-servings-text="">8 servings</span><p>Scaled ×2</p><Recipe.ServingsText> shows the recipe’s servings at the Root’s, and <Recipe.YieldText> shows its yield. For a recipe with only a yield, servings count the yield, so for 24 cookies RecipeCard shows 8 cookies. A recipe with neither renders nothing from both, which is why ScaleNote shows scale: for one, RecipeCard shows Scaled ×8.
@recipe-book/react marks its parts and hooks as Client Components, so a Server Component can render <Recipe.Root> and parts such as <Recipe.Image> as they are. ScaleNote calls a hook, so its file starts with 'use client'.
| 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 <Recipe.Provider>’s defaultSystem, then the system the recipe was written in, 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 the parts show as 10 ⅛ tbsp, rather than 10 tbsp. The unit is still the one a cook measures with. |
locale |
string | undefined |
A language tag that Intl accepts, such as 'de-DE', for formatting numbers. Defaults to the nearest provider’s locale, then 'en-US'. <Recipe.Root> doesn’t check it: with a tag Intl rejects, such as 'en_US', the parts that write numbers throw invalid_argument when they have one to write, and <Recipe.Ingredient> throws even for a line with no number, such as “salt, to taste”. In a runtime without Intl, none of them throws for any locale string, even 'en_US', and they write the numbers in English, as the ingredients page says for its parts. |
labels |
RecipeLabelPack | undefined |
A label pack, whose controls’ text is merged over the nearest provider’s labels key by key. Its language, units, durations, temperature, and size replace the provider’s pack’s whole, so a pack of the controls’ text alone writes units in English. For one language, import its pack from @recipe-book/react/labels, which covers units and the controls’ text. The packs leave out some units, such as cup, oz, the 250 mL cup-metric, and jar, which keep their English labels. <Recipe.Provider> lists all of them, and the text that stays in English. For your own text, make a pack once with its labelPack, such as at module scope: a new one each render re-renders most parts. A copy from a loader or JSON isn’t a pack. In every build, a value that isn’t a pack, such as 'de' or a plain object, throws invalid_argument, and so does a pack a Server Component passes that it didn’t import by name from a client module, such as @recipe-book/react/labels or a 'use client' module of yours: one it made, say, or core’s de from @recipe-book/react/core/labels. |
idPrefix |
string | undefined |
Comes before each step’s id in the id that <Recipe.Step> renders and in the step URLs that <Recipe.JsonLd> writes. Defaults to the recipe’s id and a hyphen, such as buttermilk-pancakes-. See Step IDs. |
children |
ReactNode | undefined |
The parts and components that read the recipe’s state. |
A <Recipe.Root> inside another doesn’t take the outer Root’s locale or labels, only the nearest <Recipe.Provider>’s, so set defaults that several recipes share on a provider.
Parse on the server
Call parseRecipe where you load recipe input, such as in a Server Component, a loader, or a build step, and pass result.data. A recipe is plain data, so it can cross from a Server Component to <Recipe.Root>, and on Next.js 14, 15, and 16, a production build keeps the parser out of the browser bundle, with webpack or, from Next.js 15.3, Turbopack. Render a recipe in React shows this in a Next.js page. With Next.js, and with Vite when each page loads as its own chunk, such as a lazy route, only the pages whose browser code imports parseRecipe, recipeSchema, createRecipeSchema, or fromJsonLd download the parser. A call to import('@recipe-book/react/core') can download it too, as Why parse on the server describes. In a production build, a page with a Next.js <Link> to one of those pages downloads the parser too once the <Link> is in view, when Next.js prerenders the linked page as static, because Next.js then prefetches the linked page’s code. To a page Next.js renders on each request, the default <Link> prefetches only the route’s data, so the parser downloads on the click, as it does for any page with prefetch={false}, and a <Link> that sets prefetch={true} downloads it once the <Link> is in view. With cacheComponents: true in next.config.ts, the default <Link> prefetches the code for the part of such a page outside its <Suspense> boundaries, so the parser downloads once the <Link> is in view if the component that parses is in that part. If it’s inside a <Suspense> boundary, the parser downloads on the click, and prefetch={true} downloads it once the <Link> is in view only when next.config.ts doesn’t set partialPrefetching: true. Otherwise, such as with esbuild’s code splitting or with Vite without lazy routes, parse on the server on every page: one page that parses in the browser can put the parser on other pages. With esbuild’s splitting, it puts the parser on every page that imports @recipe-book/core or @recipe-book/react/core, because esbuild splits by the files each page reaches and both reach the parser’s file. If that page parses with fromJsonLd, it also puts the parser on every page that imports @recipe-book/core/schema-org or @recipe-book/react/core/schema-org.
TypeScript rejects recipe input. Input typed any, such as the result of response.json(), gets past TypeScript, so <Recipe.Root> checks the shape of each new recipe, including each ingredient and step, and throws invalid_argument for one whose shape is wrong, such as recipe input:
RecipeBookError: <Recipe.Root>: 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/It checks that equipment, notes, and times.custom are arrays, but not the items in them. A recipe you build with a null equipment item, note, or custom time gets past it, and the part that renders that item throws a TypeError: <Recipe.Equipment> or <Recipe.JsonLd> for an equipment item, <Recipe.Notes> for a note, and <Recipe.Times> for a custom time.
It doesn’t check that IDs are unique, as they are in a recipe parseRecipe returns. In a recipe you build, give each ingredient an id that no other ingredient has, and each step one that no other step has, even in another section. Parts use them as React keys. Two ingredients or two steps with one id tick together in a <Recipe.Checklist>, and <Recipe.Step> renders the same id for two such steps.
Parse in the browser
To render recipe input that exists only in the browser, such as the text in a recipe editor, parse it in a Client Component and pass result.data. When parsing fails, render something else in place of <Recipe.Root>:
'use client'
import { parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useMemo } from 'react'
export function RecipePreview({ input }: { input: unknown }) {
const result = useMemo(() => parseRecipe(input), [input])
if (!result.success) {
return <p>This recipe cannot be shown.</p>
}
return (
<Recipe.Root recipe={result.data}>
<Recipe.Image />
</Recipe.Root>
)
}To show what to fix, such as in a recipe editor, list result.error.issues when parsing fails, or result.warnings when it succeeds, as Read issues shows. Each issue has a code, such as unknown_field, a path to the value, and a message.
The page then downloads the parser, as Parse on the server describes.
Read ingredient lines
parseRecipe reads ingredients written as text, such as '2 cups flour', only when you pass it parseIngredientLine:
'use client'
import { parseIngredientLine, parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useMemo } from 'react'
export function RecipePreview({ input }: { input: unknown }) {
const result = useMemo(
() => parseRecipe(input, { parseIngredientLine }),
[input],
)
if (!result.success) {
return <p>This recipe cannot be shown.</p>
}
return (
<Recipe.Root recipe={result.data}>
<Recipe.Ingredients />
</Recipe.Root>
)
}For recipe input with ingredients: ['1 ½ cups flour', '1 ¼ cups buttermilk'], <Recipe.Ingredients> lists the quantity and name parsed from each line. Without parseIngredientLine, each line is an invalid_type issue whose message names the option, so parsing fails. For regional recipes, pass decimal or units in the same object as parseIngredientLine: parseRecipe(input, { parseIngredientLine, decimal, units }).
With Next.js, and with Vite when each page loads as its own chunk, such as a lazy route, only the pages that import parseIngredientLine or fromJsonLd, such as to pass parseIngredientLine to parseRecipe, download the line parser. A call to import('@recipe-book/react/core') can download it too, as Why parse on the server describes. In a production build, a page with a Next.js <Link> to one of those pages downloads the line parser too once the <Link> is in view, when Next.js prerenders the linked page as static, because Next.js then prefetches the linked page’s code. To a page Next.js renders on each request, the default <Link> prefetches only the route’s data, so the line parser downloads on the click, as it does for any page with prefetch={false}, and a <Link> that sets prefetch={true} downloads it once the <Link> is in view. With cacheComponents: true in next.config.ts, the default <Link> prefetches the code for the part of such a page outside its <Suspense> boundaries, so the line parser downloads once the <Link> is in view if the component that parses is in that part. If it’s inside a <Suspense> boundary, the line parser downloads on the click, and prefetch={true} downloads it once the <Link> is in view only when next.config.ts doesn’t set partialPrefetching: true. Write ingredients as text shows what a line can hold.
Controlled and uncontrolled state
By default, <Recipe.Root> keeps the number of servings and the measurement system itself, starting from defaultServings and defaultSystem. Pass servings to control servings instead: <Recipe.Root> shows that number, and setServings calls onServingsChange without changing it. Controlled servings live in your own state, so you can control servings from outside the Root too, such as from a button. A component there can’t get setServings from useRecipe(), which throws missing_parent outside a Root.
'use client'
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useState } from 'react'
export function ScaledRecipe({ recipe }: { recipe: ParsedRecipe }) {
const [servings, setServings] = useState(8)
return (
<Recipe.Root
recipe={recipe}
servings={servings}
onServingsChange={setServings}
>
<Recipe.Image />
</Recipe.Root>
)
}On React 19, to save servings in a transition, such as with a Server Action, pass the value from useOptimistic as servings, and set it first in the transition: each pick shows at once, and once the transition ends, the Root shows your state again, so a save that fails goes back to the servings you last saved.
Servings from useActionState are controlled too when you pass them as servings, so keep the reader’s pick in state of your own, as with servings={picked ?? state.servings} and onServingsChange={setPicked}. Until the reader picks, the Root shows the state’s servings, so the state needs them from the start, such as by starting useActionState with the saved servings, and in every state the action returns, errors included. Otherwise servings switch between controlled and uncontrolled, and in development the Root warns. Without onServingsChange, servings from the state are read-only: the select goes back to the saved number as soon as the reader picks another, so the form sends the saved number, and the input goes back to it once it loses focus. To start from the saved servings and let the Root keep the reader’s changes, pass them as defaultServings instead, as Save the reader’s choices with a form action does.
system and onSystemChange work the same way. Each piece of state is controlled whenever its value isn’t undefined:
- Read-only state.
servingswithoutonServingsChangecan’t change, sosetServingsdoes nothing. In development,<Recipe.Root>warns. - Switching modes. Changing
servingsfromundefinedto a number, or back, switches between uncontrolled and controlled. In development,<Recipe.Root>warns. After switching back to uncontrolled,<Recipe.Root>shows the servings it had before they were controlled, not the last controlled number. If servings started controlled, that’sdefaultServings, or the scaling base without it. - Resets. Uncontrolled state goes back to its defaults when the recipe’s
idchanges, so each recipe starts at its own servings. The reset doesn’t callonServingsChangeoronSystemChange. To reset servings from a button of your own, callsetServingswith the number to go back to, such as the scaling base, or, from a button outside the Root, set your controlled servings to that number.
Scaling base
The number of servings counts from the recipe’s scaling base: its servings amount, else its yield amount, else 1, so a recipe with a yield but no servings counts servings in the yield’s unit. It skips an amount that isn’t a finite number greater than 0, which only a recipe you build can have, so servings of 0 count as none. scale is the number of servings divided by the base.
Servings window
<Recipe.Root> accepts a number of servings from a millionth to a million times the recipe’s scaling base, including both ends. It rejects a number outside that window rather than clamping it to the minimum or maximum, so the state never reports servings that nobody set:
setServingsignores it.- A controlled
servingsshowsdefaultServingsinstead. - A
defaultServingsfalls back to the scaling base.
Each case logs a development warning that names the window for the recipe. It rounds the minimum and maximum to six significant digits toward the inside of the window, so every number it names is accepted: for ⅔ servings, the maximum it names is 666666. For the sample recipe, which has 4 servings, defaultServings={0} logs:
Recipe Book: `defaultServings` must be a number from 0.000004 to 4000000 for this recipe, received 0. Using 4 instead.
See https://recipe-book.siraj.page/errors/#warning-invalid-default-servingsAnd setServings(0) logs:
Recipe Book: setServings() expects a number from 0.000004 to 4000000 for this recipe, but received 0. The value was ignored.
See https://recipe-book.siraj.page/errors/#warning-invalid-set-servingsWhen a recipe with the same id and another scaling base replaces the recipe, uncontrolled servings it can’t take show defaultServings, or the scaling base without it, with no warning, since you passed no number outside the window. With uncontrolled servings, after a swap to any recipe with another scaling base, whatever its id, a setServings from before the swap still checks the replaced recipe’s window, so a number it accepts that the new recipe can’t take shows defaultServings, or the new recipe’s scaling base without it, with a development warning.
<Recipe.Root> rejects a measurement system other than 'metric' or 'us' the same way: setSystem ignores it, and a controlled system shows the default system instead, each with a development warning. A defaultSystem other than those two counts as missing, on the Root and on every provider, with a development warning too. For a recipe written in metric, <Recipe.Root defaultSystem="imperial"> inside <Recipe.Provider defaultSystem="us"> starts in US units.
To start a Root at servings or a system from a link or a cookie, read them with readRecipeView, which applies the same window and checks, so a value it returns never logs a warning. Share servings in a link and Remember the reader’s choice show it with Next.js.
Step IDs
Each <Recipe.Step> renders an id: the Root’s idPrefix, then the step’s id. <Recipe.JsonLd> writes the same IDs, percent-encoded, as the fragments of its step URLs, so with both in one Root, each step URL points at its step. Inside the Root, useRecipe() returns the prefix as idPrefix, so `#${idPrefix}${step.id}` links to a step.
idPrefix defaults to the recipe’s id and a hyphen, so the sample recipe’s first step is buttermilk-pancakes-step-1. A recipe without an id of its own, or with one that String.prototype.trim leaves empty, such as ' ', gets one from its name when it’s parsed. An id loses the whitespace at its ends, so ' x ' gives x-step-1. The parsed recipe carries that id, so the server and the browser render the same IDs on every React version. The name’s letters and digits, in any script, are kept and lowercased. Each run of anything else, such as spaces, punctuation, symbols, or emoji, becomes one hyphen, with none at either end:
- Accents on Latin letters are dropped, so
Crème brûléegivescreme-brulee-step-1. - Other scripts keep their letters and marks, so
パンケーキgivesパンケーキ-step-1, which<Recipe.JsonLd>percent-encodes. - Compatibility characters are spelled out, so
½gives1-2. - A name with no letters or digits in its NFKD form, such as
🥞🥞or¡!, givesrecipe, so its steps arerecipe-step-1. An empty name doesn’t parse.
Renaming a recipe without an id of its own changes its step IDs, so write it one to keep links to its steps working.
A step ID can start with a digit, such as 16d0955c-step-2 for a recipe whose id is 16d0955c, or 5-minute-pancakes-step-1 for one named 5-minute pancakes. Links to it and getElementById work, but querySelector() throws a SyntaxError for #16d0955c-step-2, and a stylesheet drops a rule with that selector. Escape the ID, with CSS.escape in a script or as #\31 6d0955c-step-2 in a stylesheet, or give the Root an idPrefix that starts with a letter.
Two recipes with the same id on one page need their own idPrefix, such as `featured-${recipe.id}-`, and so does one recipe rendered twice. Their Roots would otherwise give their steps the same IDs, and a link would reach only the first. Keep the recipe’s id in the prefix: two featured recipes that each use "featured-" can both render featured-step-1. Two recipes without an id get the same one from the same name, or from names such as Crème brûlée and Creme brulee. In development, the second of two mounted Roots with the same idPrefix warns once, but only when both have a <Recipe.Step> that renders an id from it. The Roots check in the browser after they mount, so the server never warns, and Roots from two copies of @recipe-book/react never compare their prefixes. Roots that render recipe cards can share a prefix, since nothing collides. A Root that renders only <Recipe.JsonLd>, such as one in the page’s <head>, can keep the default, and its step URLs point at the steps of the Root with the same recipe when that Root keeps the default too, since the steps and <Recipe.JsonLd> need the same idPrefix.
With cacheComponents: true, Next.js keeps the last few pages a reader navigated away from in the document, hidden, so they keep their state if the reader goes back. A recipe on the page the reader is on and on one they left then has each step ID twice. That needs no idPrefix: Next.js puts the page the reader is on first, so links and getElementById reach its steps. But document.querySelectorAll('[data-recipe-step]') finds the hidden pages’ steps too, so query within the page’s own element, such as its <main>. Don’t rely on :target for links within the app either: a <Link> to a step on another page changes the URL with history.pushState, which doesn’t update :target, so a [data-recipe-step]:target style doesn’t show on the step.
To choose the IDs, such as step-1 or pancakes-step-1, set idPrefix to "" or "pancakes-":
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
export function PancakeSteps({ recipe }: { recipe: ParsedRecipe }) {
return (
<Recipe.Root recipe={recipe} idPrefix="pancakes-">
<Recipe.StepList />
</Recipe.Root>
)
}For the sample recipe, PancakeSteps renders:
<ol start="1" data-recipe-step-list="">
<li id="pancakes-step-1" data-recipe-step=""><span data-recipe-step-text="">Whisk the dry ingredients in a large bowl.</span></li>
<li id="pancakes-step-2" data-recipe-step=""><span data-recipe-step-text="">Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.</span></li>
<li id="pancakes-step-3" data-recipe-step=""><span data-recipe-step-text="">Cook ¼-cup portions on a buttered griddle, <span data-recipe-duration="">2–3 minutes</span> per side.</span></li>
</ol>A step rendered twice in one Root renders one id twice. Pass id={undefined} to one of the two <Recipe.Step>s to render none there.
Wrap Root
To wrap <Recipe.Root>, intersect its props type, RecipeRootProps, with your own props, and pass the rest on with a spread:
import * as Recipe from '@recipe-book/react'
type RecipeCardProps = Recipe.RecipeRootProps & {
title: string
}
export function RecipeCard({ title, ...props }: RecipeCardProps) {
return (
<article>
<h2>{title}</h2>
<Recipe.Root {...props} />
</article>
)
}Named imports
To import <Recipe.Root> by name, import Root. If the name clashes with one of yours, alias it, as in import { Root as RecipeRoot } from '@recipe-book/react'.