Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readReact

Render a React context as its provider

Render a context object as a provider in React 19 and keep the same value, readers and nested overrides.

If your app requires React 19, you can shorten <DensityContext.Provider> to <DensityContext>. Keep the same value prop and the same context readers.

Render the context object

React 19 accepts the context object as a provider. Give it the same value and children. Search for the opening and closing .Provider tags and change them as a pair.

Both rows read the same context. The settings row gets the page's roomy value. The preview overrides it with compact.

import { createContext, useContext } from 'react'

const DensityContext = createContext('roomy')

function Row({ children }) {
  const density = useContext(DensityContext)
  return <p data-density={density}>{children}</p>
}

export default function Settings() {
  return (
    <DensityContext value="roomy">
      <Row>Settings row</Row>
      <section aria-label="Preview">
        <DensityContext value="compact">
          <Row>Preview row</Row>
        </DensityContext>
      </section>
    </DensityContext>
  )
}

Inspect the two paragraphs and you will see data-density="roomy" on Settings row and data-density="compact" on Preview row.

Keep the provider above the reader

The nearest matching provider above a reader supplies its value. A provider inside a component's return cannot change the result of useContext called at the top of that same component. Here the reads happen inside Row, beneath the provider that should supply each value. If a read still gets the fallback, inspect where the reader sits in the tree before editing the default.

An omitted value also differs from an absent provider. With a provider and no value, a child receives undefined. The roomy passed to createContext applies when a reader has no matching provider above it. After migrating, inspect both rows to verify that the preview still receives the nested value.

Keep .Provider in shared code that still supports React 18.