2.7Guides
Render a recipe in React
Parse a recipe in a Server Component and render it with <Recipe.Root>, or parse recipe input in the browser.
Parse a recipe in a Next.js App Router page, pass it to <Recipe.Root>, render its steps, add a servings control, and let readers switch units. Then parse recipe input in the browser, for when the input exists only there. In a single-page app, such as a Vite app, parse at the top of a module, as the quickstart does, and render the same <Recipe.Root> from any component, with the quickstart’s recipe in place of result.data. With React Router in framework mode, parse in a route’s loader, as Render a recipe on the server shows, use its loaderData in place of result.data, and throw data(null, { status: 404 }), imported from react-router, in place of notFound(). The guide’s file names are Next.js paths, so import each component from where you save it. Vite ignores the guide’s 'use client' lines.
Parse on the server
The page uses the sample recipe from the Next.js example:
import type { RecipeInput } from '@recipe-book/react/core'
export const pancakes = {
name: 'Buttermilk pancakes',
image: '/pancakes.svg',
servings: 4,
times: { prep: 10, cook: 15 },
ingredients: [
{ name: 'all-purpose flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
{ name: 'sugar', quantity: '2 tbsp', equivalents: ['25 g'] },
{ name: 'baking powder', quantity: '2 tsp' },
{ name: 'buttermilk', quantity: '1 ¼ cups' },
{ name: 'egg', plural: 'eggs', quantity: 2 },
{
name: 'butter',
quantity: '3 tbsp',
note: 'melted',
equivalents: ['42 g'],
},
{ name: 'maple syrup', note: '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.',
],
} satisfies RecipeInputThe page in this guide doesn’t show the recipe’s image. To show it, save the Next.js example’s image in your app’s public/ folder:
<svg xmlns="http://www.w3.org/2000/svg" width="600" height="400" viewBox="0 0 600 400">
<rect width="600" height="400" fill="#fdf3e1"/>
<ellipse cx="300" cy="322" rx="236" ry="48" fill="#e6e0d6"/>
<ellipse cx="300" cy="314" rx="204" ry="36" fill="#fff"/>
<g fill="#d99a4e" stroke="#b0702b" stroke-width="4">
<ellipse cx="300" cy="288" rx="164" ry="34"/>
<ellipse cx="300" cy="250" rx="164" ry="34"/>
<ellipse cx="300" cy="212" rx="164" ry="34"/>
<ellipse cx="300" cy="174" rx="164" ry="34"/>
</g>
<ellipse cx="300" cy="168" rx="152" ry="26" fill="#e9b56d"/>
<g fill="#8c4a12">
<ellipse cx="300" cy="166" rx="104" ry="18"/>
<rect x="206" y="166" width="16" height="58" rx="8"/>
<rect x="352" y="170" width="16" height="84" rx="8"/>
</g>
<path d="M276 140h52l-8 22h-52z" fill="#fff3b0" stroke="#e3c75e" stroke-width="3" stroke-linejoin="round"/>
</svg>Then render <Recipe.Image>, as the example does with Next.js’s Image. If you render the quickstart’s recipe, add image: '/pancakes.svg' to its input, since <Recipe.Image> renders nothing without an image.
The page is a React Server Component (RSC). It looks up the recipe input by its slug, parses it with parseRecipe, and passes result.data to <Recipe.Root>:
import { parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { notFound } from 'next/navigation'
import { pancakes } from '../../recipe'
import { ServingsStepper } from './servings-stepper'
const recipes: Record<string, unknown> = { pancakes }
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const result = parseRecipe(recipes[slug])
if (!result.success) notFound()
return (
<Recipe.Root recipe={result.data}>
<h1>{result.data.name}</h1>
<ServingsStepper />
<h2>Method</h2>
<Recipe.Steps />
</Recipe.Root>
)
}For an unknown slug, recipes[slug] is undefined, parsing fails, and notFound() renders the 404 page. @recipe-book/react marks <Recipe.Root> and its parts, such as <Recipe.Steps>, as Client Components, so the page renders them without 'use client' of its own. @recipe-book/react/core isn’t a 'use client' module, so parseRecipe runs on the server. result.data is plain data, so it crosses from the page to <Recipe.Root>.
A component that reads the recipe’s state with useRecipe() is a Client Component too. This one shows the servings, or the yield for a recipe without servings, between minus and plus buttons, which change them with setServings:
'use client'
import * as Recipe from '@recipe-book/react'
export function ServingsStepper() {
const { servings, setServings, scaledServings } = Recipe.useRecipe()
return (
<div role="group" aria-label="Servings">
<button
aria-label="Fewer servings"
aria-disabled={servings <= 1 ? true : undefined}
onClick={() => servings > 1 && setServings(servings - 1)}
>
−
</button>
<output>
{scaledServings ? <Recipe.ServingsText /> : <Recipe.YieldText />}
</output>
<button
aria-label="More servings"
onClick={() => setServings(servings + 1)}
>
+
</button>
</div>
)
}At 1 serving, Fewer servings has aria-disabled rather than disabled, so it keeps the keyboard focus.
If your next.config.ts sets cacheComponents: true, as create-next-app 16.4 and later do by default for an App Router project, Next.js can’t prerender this page as it stands, because it reads params: next dev logs an error and next build fails. For a known set of recipes, such as recipes here, export generateStaticParams from the page to list their slugs, so Next.js prerenders each recipe’s page when it builds. next dev still logs an error for a slug the page answers with notFound(), such as one not in recipes, and for every slug when next.config.ts also sets partialPrefetching: true, as create-next-app does, unless the page also exports instant = false, which lets a link to the page wait for it rather than show a loading state:
export const instant = false
export function generateStaticParams() {
return Object.keys(recipes).map((slug) => ({ slug }))
}For recipes you can’t list when you build, instant = false alone has Next.js render each page when it’s requested. Or add a loading state next to the page, which shows at once:
export default function Loading() {
return <p>Loading…</p>
}The page then streams in behind the loading state, so a <Link> to one of its steps from another page, such as to /recipes/pancakes#buttermilk-pancakes-step-2, opens the page at the top rather than at the step. Opening the URL directly can too: the browser looks for the step only until the page has loaded, and React can show the page after that. With instant = false alone, both reach the step.
Inside your layout, /recipes/pancakes renders this HTML with server-side rendering (SSR):
<h1>Buttermilk pancakes</h1><div role="group" aria-label="Servings"><button aria-label="Fewer servings">−</button><output><span data-recipe-servings-text="">4 servings</span></output><button aria-label="More servings">+</button></div><h2>Method</h2><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="">Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.</span></li><li id="buttermilk-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></div></div><Recipe.ServingsText> words the servings as the servings parts do, so a range such as 6–8 reads 6–8 servings at the recipe’s own servings. For a recipe with only a yield, <Recipe.YieldText> shows it instead, such as 24 cookies. After React hydrates the page, More servings changes the stepper to 5 servings. The steps don’t change with the servings, so they don’t re-render.
A recipe with warnings still parses, and <Recipe.Root> doesn’t report them. Check result.warnings in the page, as Handle warnings shows.
Server-render a recipe parses on the server with the Next.js Pages Router, React Router, Astro, and your own server too, and shows what changes once React hydrates the page.
Let readers switch units
<Recipe.SystemToggle> lets readers switch the recipe between metric and US units. It sets the measurement system in <Recipe.Root>, and <Recipe.Ingredients> lists the recipe’s ingredients at the Root’s servings and in its system. Render both in page.tsx:
<Recipe.Root recipe={result.data}>
<h1>{result.data.name}</h1>
<ServingsStepper />
<Recipe.SystemToggle />
<Recipe.Ingredients />
<h2>Method</h2>
<Recipe.Steps />
</Recipe.Root>The sample recipe is written in US units, so US starts checked and the list shows the quantities as written. The two parts render this HTML, indented here for reading. It has 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”:
<div aria-label="Measurement system" role="radiogroup" data-recipe-system-toggle="">
<button autoComplete="off" type="button" role="radio" aria-checked="false" tabindex="-1" data-recipe-system-option="" data-state="unchecked">Metric</button>
<button autoComplete="off" type="button" role="radio" aria-checked="true" tabindex="0" data-recipe-system-option="" data-state="checked">US</button>
</div>
<div data-recipe-ingredients="">
<div data-recipe-ingredient-section="">
<ul data-recipe-ingredient-list="">
<li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">1 ½ cups</span> <span data-recipe-ingredient-name="">all-purpose flour</span></li>
<li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">2 tbsp</span> <span data-recipe-ingredient-name="">sugar</span></li>
<li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">2 tsp</span> <span data-recipe-ingredient-name="">baking powder</span></li>
<li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">1 ¼ cups</span> <span data-recipe-ingredient-name="">buttermilk</span></li>
<li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">2</span> <span data-recipe-ingredient-name="">eggs</span></li>
<li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">3 tbsp</span> <span data-recipe-ingredient-name="">butter</span>, <span data-recipe-ingredient-note="">melted</span></li>
<li data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span>, <span data-recipe-ingredient-note="">to serve</span></li>
</ul>
</div>
</div>After a click on Metric, the flour uses the recipe’s gram equivalent, and the buttermilk converts to milliliters. Teaspoons and tablespoons belong to both systems, so the sugar and butter keep the spoon measures they were written in. Only the flour and buttermilk items change:
<li data-recipe-ingredient="" data-origin="equivalent"><span data-recipe-ingredient-quantity="">190 g</span> <span data-recipe-ingredient-name="">all-purpose flour</span></li>
<li data-recipe-ingredient="" data-origin="converted"><span data-recipe-ingredient-quantity="">296 mL</span> <span data-recipe-ingredient-name="">buttermilk</span></li>To build a list of your own, read ingredients from useRecipe(): each section’s ingredients at the Root’s servings and in its 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 Root’s exact is set. In 'us', quarts, pints, gallons, and fluid ounces are only scaled, and at a scale within 1e-9 of 1, an amount in its own system and unit stays as written, but a range whose min equals its max gives its min.
Why parse on the server
- The parser stays out of the browser.
parseRecipeand the schemas that wrap it are the largest imports in@recipe-book/react/core. When every page parses on the server, only the parsed recipe reaches the browser, 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. With Next.js, and with Vite when each page loads as its own chunk, such as a lazy route, a page that parses on the server stays free of the parser even if another page parses in the browser withimport { parseRecipe } from '@recipe-book/react/core', unless it has a Next.js<Link>that prefetches that page’s code, as Parse on the server describes. Callingimport('@recipe-book/react/core')can still download a parser: with Next.js, on the page that calls it, and with Vite, on that page and sometimes on other pages that import from@recipe-book/react/core, when Vite puts their imports in the parser’s chunk. With both, a declaration that destructures only named bindings, such asconst { formatQuantity } = await import('@recipe-book/react/core'), downloads only what those names use. Using the module as an object, such ascore.formatQuantity, downloadsparseRecipeandparseIngredientLinewhen a declaration holds it, such asconst core = await import('@recipe-book/react/core'). Whencoreis a.thencallback’s parameter instead, such as.then((core) => core.formatQuantity(quantity)), Next.js downloads both and Vite downloads neither. A...restbinding downloads both too, and so does destructuring in a.thencallback with Next’s webpack build. The forms that don’t download both still download a parser when another page’simport()of the module downloads one, or, except with Next’s webpack build, when another page parses in the browser withimport { parseRecipe },import { parseIngredientLine }, orimport { fromJsonLd }. With Vite 8.3, if another lazy page parses in the browser withimport { parseRecipe }orimport { parseIngredientLine }and hasn’t loaded yet, theimport()in the destructuring declaration and in both.thenforms can reject with aTypeError, depending on how Vite splits the chunks, and that other page then fails to load until the next full page load. A staticimport { formatQuantity } from '@recipe-book/react/core'in place of theimport()works, and in a lazy route it doesn’t download the other page’s parser. Replace every suchimport()in the app: while one page keeps it, a lazy page with the static import can reject with the sameTypeErrortoo. - Server and browser render the same recipe. The browser gets the recipe the server parsed, so hydration starts from the same data.
Render your own steps
To add a <Recipe.Checklist>, render <Recipe.Checklist><Recipe.Steps /></Recipe.Checklist> in the page in place of <Recipe.Steps />, and each step gets a checkbox that readers can tick as they cook. To render the steps your own way, pass a render function to <Recipe.StepList>, as below, or to <Recipe.Steps> for each section, from a Client Component. This one labels each checkbox with the step’s number, and shows the step’s text below it:
'use client'
import * as Recipe from '@recipe-book/react'
export function Method() {
return (
<Recipe.Checklist>
<Recipe.StepList>
{(step) => (
<Recipe.Step item={step}>
<label>
<Recipe.StepCheckbox /> <span>{`Step ${step.number}`}</span>
</label>
<p><Recipe.StepText /></p>
</Recipe.Step>
)}
</Recipe.StepList>
</Recipe.Checklist>
)
}In the page, render <Method /> in place of <Recipe.Steps />. It reads the recipe from the page’s <Recipe.Root>, so it takes no props. /recipes/pancakes now renders the steps as:
<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>Step 1</span></label><p><span data-recipe-step-text="">Whisk the dry ingredients in a large bowl.</span></p></li>
<li id="buttermilk-pancakes-step-2" data-recipe-step=""><label><input autoComplete="off" type="checkbox" data-recipe-step-checkbox=""/> <span>Step 2</span></label><p><span data-recipe-step-text="">Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.</span></p></li>
<li id="buttermilk-pancakes-step-3" data-recipe-step=""><label><input autoComplete="off" type="checkbox" data-recipe-step-checkbox=""/> <span>Step 3</span></label><p><span data-recipe-step-text="">Cook ¼-cup portions on a buttered griddle, <span data-recipe-duration="">2–3 minutes</span> per side.</span></p></li>
</ol>A render function written in the page itself fails to render, because a function can’t cross from a Server Component to a Client Component. The Ingredients reference shows the error.
Let readers change servings
ServingsStepper is your own component. @recipe-book/react also has two servings controls: <Recipe.ServingsSelect> offers ½×, 1×, 2×, and 3× the recipe’s scaling base, each rounded to a whole number of at least 1, and <Recipe.ServingsInput> takes a typed number. Neither needs a function prop, so the page, a Server Component, can render them directly.
In the page, render <Recipe.ServingsSelect /> next to <ServingsStepper />. /recipes/pancakes now renders the select as:
<select autoComplete="off" aria-label="Servings" data-recipe-servings-select="">
<option value="2">2 servings</option>
<option value="4" selected="">4 servings</option>
<option value="8">8 servings</option>
<option value="12">12 servings</option>
</select>Both controls read and set the same Root’s servings. Choosing 8 servings changes the stepper to 8 servings and the flour to 3 cups, and More servings then adds 9 servings to the select and selects it.
To let readers type a number, render <Recipe.ServingsInput /> instead. When it commits lists the numbers it accepts.
The Servings reference shows how to rename both parts for screen readers, and how the select words its options for a recipe that has a yield but no servings.
Parse in the browser
Some recipe input exists only in the browser, such as the text in a recipe editor. To render it, call parseRecipe in a Client Component and pass result.data to <Recipe.Root>. When parsing fails, render something else in its place:
'use client'
import { parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useMemo } from 'react'
import { ServingsStepper } from './recipes/[slug]/servings-stepper'
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}>
<h2>Preview</h2>
<ServingsStepper />
</Recipe.Root>
)
}For the sample recipe, RecipePreview renders the heading and the stepper at 4 servings. For { name: 'Buttermilk pancakes', servings: 0 }, it renders <p>This recipe cannot be shown.</p>, and result.error.message says why:
"Buttermilk pancakes" has 3 problems:
✖ servings Expected a positive number, received 0.
⚠ ingredients Recipe has no ingredients.
⚠ steps Recipe has no steps.
See https://recipe-book.siraj.page/errors/invalid_recipe/useMemo parses again only when input changes, so give RecipePreview input that keeps its identity between renders. Parse in the browser explains why. For ingredients written as text, Read ingredient lines shows how to pass parseIngredientLine to parseRecipe.
Edit with Fast Refresh
Fast Refresh keeps servings, system, cook mode, and the Checklist’s ticks when you edit a component under <Recipe.Root>, or the component that renders the Root, without changing its hooks. Changing what a useMemo or useEffect call runs, or its dependencies, keeps them. Adding, removing, or reordering hooks in the component that renders the Root resets them all, and so does renaming a variable that holds a hook’s result or changing the initial value passed to useState or useReducer, because Fast Refresh remounts a component whose hooks change.
Use the React Compiler
Recipe Book works in apps built with the React Compiler, with nothing to configure. @recipe-book/react ships uncompiled, and its hooks return new objects and arrays when anything in them changes, so your compiled components update. On React 18, the compiler needs its target option set to '18' and the react-compiler-runtime package for your own code, as the compiler’s docs say. Recipe Book doesn’t add that package, so install it in your app.
Next steps
- Root for every prop, controlled state, and the servings window
- Hooks for
useRecipe,useRecipeState, the state they return, anduseFormatIngredient - Image for the recipe’s image
- Steps for sections, numbering, and rendering your own steps
- Servings for the servings select and input
- SystemToggle for the units toggle, its options, and their keyboard behavior
- Ingredients for the parts that list a recipe’s ingredients
- Times, Equipment, Notes, and Nutrition for the rest of a recipe card
- JSON-LD for the schema.org Recipe JSON-LD that search engines read
- Provider for defaults shared by every Root
missing_parentfor a component rendered outside<Recipe.Root>- Style a recipe for styling the parts with
className,style, and their data attributes - Make a recipe accessible for translated labels, names that match your layout, heading levels, and keyboard behavior