use

use is a React API that lets you read a resource during rendering, such as a Promise or context.

const value = use(resource);

Reference

use(context)

Call use with a context to read its value. Unlike useContext, use can be called within loops and conditional statements like if.

import { use } from 'react';

function Button() {
  const theme = use(ThemeContext);
  // ...

See more examples below.

Parameters

Returns

The context value for the passed context, determined by the closest context provider above the calling component. If there is no provider, the returned value is the defaultValue passed to createContext.

Caveats

  • use must be called inside a Component or a Hook.
  • Reading context with use is not supported in Server Components.

use(promise)

Call use with a Promise to read its resolved value. The component calling use suspends while the Promise is pending. Despite its name, use is not a Hook. Unlike Hooks, it can be called inside loops and conditional statements like if.

import { use } from 'react';

function MessageComponent({ messagePromise }) {
  const message = use(messagePromise);
  // ...

If the component that calls use is wrapped in a Suspense boundary, the fallback will be displayed while the Promise is pending. Once the Promise is resolved, the Suspense fallback is replaced by the rendered components using the data returned by use. If the Promise is rejected, the fallback of the nearest Error Boundary will be displayed.

See more examples below.

Parameters

  • promise: A Promise whose resolved value you want to read. The Promise must be cached so that the same instance is reused across re-renders.

Returns

The resolved value of the Promise.

Caveats

  • use must be called inside a Component or a Hook.
  • use cannot be called inside a try-catch block. Instead, wrap your component in an Error Boundary to catch the error and display a fallback.
  • Promises passed to use must be cached so the same Promise instance is reused across re-renders. See caching Promises below.
  • When passing a Promise from a Server Component to a Client Component, its resolved value must be serializable.

use(browser())

Call use with the value returned by browser in a component that should only render in the browser:

import { use } from 'react';
import { browser } from 'react-dom';

function BrowserOnly() {
  use(browser('This component requires browser APIs.'));
  return <BrowserContent />;
}

During server rendering, the component calling use(browser()) suspends and React includes the closest <Suspense> boundary's fallback in the HTML. In the browser, use(browser()) returns undefined, so the component renders normally.

See an example below.

Parameters

  • browserValue: The value returned by browser.

Returns

use(browser()) returns undefined in the browser.

Caveats

  • The component calling use(browser()) must be inside a <Suspense> boundary during server rendering. Without one, server rendering fails.
  • In a React Server Components app, use(browser()) must be called from a Client Component, not a Server Component.

Usage (Context)

Reading context with use

When a context is passed to use, it works similarly to useContext. While useContext must be called at the top level of your component, use can be called inside conditionals like if and loops like for.

```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { use } from 'react';

function Button() { const theme = use(ThemeContext); // ...


`use` returns the &lt;CodeStep step={2}>context value&lt;/CodeStep> for the &lt;CodeStep step={1}>context&lt;/CodeStep> you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context.

To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider.

```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]]
function MyPage() {
  return (
    <ThemeContext value="dark">
      <Form />
    </ThemeContext>
  );
}

function Form() {
  // ... renders buttons inside ...
}

It doesn't matter how many layers of components there are between the provider and the Button. When a Button anywhere inside of Form calls use(ThemeContext), it will receive "dark" as the value.

Unlike useContext, <CodeStep step={2}>use</CodeStep> can be called in conditionals and loops like <CodeStep step={1}>if</CodeStep>.

```js [[1, 2, "if"], [2, 3, "use"]] function HorizontalRule({ show }) { if (show) { const theme = use(ThemeContext); return


; } return false; }


&lt;CodeStep step={2}>`use`&lt;/CodeStep> is called from inside a &lt;CodeStep step={1}>`if`&lt;/CodeStep> statement, allowing you to conditionally read values from a Context.

> [!WARNING]
>
> Like `useContext`, `use(context)` always looks for the closest context provider *above* the component that calls it. It searches upwards and **does not** consider context providers in the component from which you're calling `use(context)`.
>

```js
import { createContext, use } from 'react';

const ThemeContext = createContext(null);

export default function MyApp() {
  return (
    <ThemeContext value="dark">
      <Form />
    </ThemeContext>
  )
}

function Form() {
  return (
    <Panel title="Welcome">
      <Button show={true}>Sign up</Button>
      <Button show={false}>Log in</Button>
    </Panel>
  );
}

function Panel({ title, children }) {
  const theme = use(ThemeContext);
  const className = 'panel-' + theme;
  return (
    <section className={className}>
      <h1>{title}</h1>
      {children}
    </section>
  )
}

function Button({ show, children }) {
  if (show) {
    const theme = use(ThemeContext);
    const className = 'button-' + theme;
    return (
      <button className={className}>
        {children}
      </button>
    );
  }
  return false
}
.panel-light,
.panel-dark {
  border: 1px solid black;
  border-radius: 4px;
  padding: 20px;
}
.panel-light {
  color: #222;
  background: #fff;
}

.panel-dark {
  color: #fff;
  background: rgb(23, 32, 42);
}

.button-light,
.button-dark {
  border: 1px solid #777;
  padding: 5px;
  margin-right: 10px;
  margin-top: 10px;
}

.button-dark {
  background: #222;
  color: #fff;
}

.button-light {
  background: #fff;
  color: #222;
}

Reading a Promise from context

To share asynchronous data without prop drilling, set a Promise as a context value, then read it with use(context) and resolve it with use(promise):

import { use } from 'react';
import { UserContext } from './UserContext';

function Profile() {
  const userPromise = use(UserContext);
  const user = use(userPromise);
  return <h1>{user.name}</h1>;
}

Reading the value requires two use calls because the context value itself isn't awaited. See Before you use context for alternatives to consider before reaching for context.

Wrap the components that read the Promise in a Suspense boundary so only that subtree suspends while the Promise is pending. See Usage (Promises) below for more on reading Promises with use.

[!WARNING]

When this pattern is used with Server Components, refetching the Promise requires refetching the Server Component that sets the Promise in context. Avoid setting the Promise in context high in the tree, since that would refetch large parts of the app unnecessarily.


Usage (Promises)

Reading a Promise with use

Call use with a Promise to read its resolved value. The component will suspend while the Promise is pending.

```js [[1, 4, "use(albumsPromise)"]] import { use } from 'react';

function Albums({ albumsPromise }) { const albums = use(albumsPromise); return (

    {albums.map(album => (
  • {album.title} ({album.year})
  • ))}
); }


Wrap the component that calls &lt;CodeStep step={1}>`use`&lt;/CodeStep> in a [Suspense](/reference/react/Suspense) boundary so React can show a fallback while the Promise is pending. The closest Suspense boundary above the suspending component shows its fallback. Once the Promise resolves, React reads the value with `use` and replaces the fallback with the rendered component.

#### Fetching data with `use`

In this example, `Albums` calls `use` with a cached Promise. The component suspends while the Promise is pending, and React displays the nearest Suspense fallback. Rejected Promises propagate to the nearest [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary).

```js src/App.js active
import { use, Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { fetchData } from './data.js';

export default function App() {
  return (
    <ErrorBoundary fallback={<p>Could not fetch albums.</p>}>
      <Suspense fallback={<Loading />}>
        <Albums />
      </Suspense>
    </ErrorBoundary>
  );
}

function Albums() {
  const albums = use(fetchData('/albums'));
  return (
    <ul>
      {albums.map(album => (
        <li key={album.id}>
          {album.title} ({album.year})
        </li>
      ))}
    </ul>
  );
}

function Loading() {
  return <h2>Loading...</h2>;
}

```js src/data.js hidden // Note: the way you would do data fetching depends on // the framework that you use together with Suspense. // Normally, the caching logic would be inside a framework.

let cache = new Map();

export function fetchData(url) { if (!cache.has(url)) { cache.set(url, getData(url)); } return cache.get(url); }

async function getData(url) { if (url === '/albums') { return await getAlbums(); } else { throw Error('Not implemented'); } }

async function getAlbums() { // Add a fake delay to make waiting noticeable. await new Promise(resolve => { setTimeout(resolve, 1000); });

return [{ id: 13, title: 'Let It Be', year: 1970 }, { id: 12, title: 'Abbey Road', year: 1969 }, { id: 11, title: 'Yellow Submarine', year: 1969 }, { id: 10, title: 'The Beatles', year: 1968 }]; }


```json package.json hidden
{
  "dependencies": {
    "react": "19.0.0",
    "react-dom": "19.0.0",
    "react-scripts": "^5.0.0",
    "react-error-boundary": "4.0.3"
  },
  "main": "/index.js"
}

Fetching data with useEffect

Before use, a common approach was to fetch data in an Effect and update state when the data arrives. Compared to use, this approach requires managing loading and error states manually. For more details on why fetching in an Effect is discouraged, see You Might Not Need an Effect.

```js src/App.js active import { useState, useEffect } from 'react'; import { fetchAlbums } from './data.js';

export default function App() { const [albums, setAlbums] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null);

useEffect(() => { fetchAlbums() .then(data => { setAlbums(data); setIsLoading(false); }) .catch(err => { setError(err); setIsLoading(false); }); }, []);

if (isLoading) { return

Loading...

; }

if (error) { return

Error: {error.message}

; }

return (

    {albums.map(album => (
  • {album.title} ({album.year})
  • ))}
); }


```js src/data.js hidden
export async function fetchAlbums() {
  // Add a fake delay to make waiting noticeable.
  await new Promise(resolve => {
    setTimeout(resolve, 1000);
  });

return [{
    id: 13,
    title: 'Let It Be',
    year: 1970
  }, {
    id: 12,
    title: 'Abbey Road',
    year: 1969
  }, {
    id: 11,
    title: 'Yellow Submarine',
    year: 1969
  }, {
    id: 10,
    title: 'The Beatles',
    year: 1968
  }];
}

[!WARNING]

Promises passed to use must be cached

Promises created during render are recreated on every render, which causes React to show the Suspense fallback repeatedly and prevents content from appearing.

function Albums() {
  // 🔴 `fetch` creates a new Promise on every render.
  const albums = use(fetch('/albums'));
  // ...
}

Instead, pass a Promise from a cache, a Suspense-enabled framework, or a Server Component:

// ✅ fetchData reads the Promise from a cache.
const albums = use(fetchData('/albums'));