useDeferredValue·续


Indicating that the content is stale

In the example above, there is no indication that the result list for the latest query is still loading. This can be confusing to the user if the new results take a while to load. To make it more obvious to the user that the result list does not match the latest query, you can add a visual indication when the stale result list is displayed:

```js {2}


With this change, as soon as you start typing, the stale result list gets slightly dimmed until the new result list loads. You can also add a CSS transition to delay dimming so that it feels gradual, like in the example below:

```js src/App.js
import { Suspense, useState, useDeferredValue } from 'react';
import SearchResults from './SearchResults.js';

export default function App() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  const isStale = query !== deferredQuery;
  return (
    <>
      <label>
        Search albums:
        <input value={query} onChange={e => setQuery(e.target.value)} />
      </label>
      <Suspense fallback={<h2>Loading...</h2>}>
        <div style={{
          opacity: isStale ? 0.5 : 1,
          transition: isStale ? 'opacity 0.2s 0.2s linear' : 'opacity 0s 0s linear'
        }}>
          <SearchResults query={deferredQuery} />
        </div>
      </Suspense>
    </>
  );
}

```js src/SearchResults.js import {use} from 'react'; import { fetchData } from './data.js';

export default function SearchResults({ query }) { if (query === '') { return null; } const albums = use(fetchData(/search?q=${query})); if (albums.length === 0) { return

No matches for "{query}"

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


```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.startsWith('/search?q=')) {
    return await getSearchResults(url.slice('/search?q='.length));
  } else {
    throw Error('Not implemented');
  }
}

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

const allAlbums = [{
    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
  }, {
    id: 9,
    title: 'Magical Mystery Tour',
    year: 1967
  }, {
    id: 8,
    title: 'Sgt. Pepper\'s Lonely Hearts Club Band',
    year: 1967
  }, {
    id: 7,
    title: 'Revolver',
    year: 1966
  }, {
    id: 6,
    title: 'Rubber Soul',
    year: 1965
  }, {
    id: 5,
    title: 'Help!',
    year: 1965
  }, {
    id: 4,
    title: 'Beatles For Sale',
    year: 1964
  }, {
    id: 3,
    title: 'A Hard Day\'s Night',
    year: 1964
  }, {
    id: 2,
    title: 'With The Beatles',
    year: 1963
  }, {
    id: 1,
    title: 'Please Please Me',
    year: 1963
  }];

const lowerQuery = query.trim().toLowerCase();
  return allAlbums.filter(album => {
    const lowerTitle = album.title.toLowerCase();
    return (
      lowerTitle.startsWith(lowerQuery) ||
      lowerTitle.indexOf(' ' + lowerQuery) !== -1
    )
  });
}
input { margin: 10px; }

Deferring re-rendering for a part of the UI

You can also apply useDeferredValue as a performance optimization. It is useful when a part of your UI is slow to re-render, there's no easy way to optimize it, and you want to prevent it from blocking the rest of the UI.

Imagine you have a text field and a component (like a chart or a long list) that re-renders on every keystroke:

function App() {
  const [text, setText] = useState('');
  return (
    <>
      <input value={text} onChange={e => setText(e.target.value)} />
      <SlowList text={text} />
    </>
  );
}

First, optimize SlowList to skip re-rendering when its props are the same. To do this, wrap it in memo:

```js {1,3} const SlowList = memo(function SlowList({ text }) { // ... });


However, this only helps if the `SlowList` props are *the same* as during the previous render. The problem you're facing now is that it's slow when they're *different,* and when you actually need to show different visual output.

Concretely, the main performance problem is that whenever you type into the input, the `SlowList` receives new props, and re-rendering its entire tree makes the typing feel janky. In this case, `useDeferredValue` lets you prioritize updating the input (which must be fast) over updating the result list (which is allowed to be slower):

```js {3,7}
function App() {
  const [text, setText] = useState('');
  const deferredText = useDeferredValue(text);
  return (
    <>
      <input value={text} onChange={e => setText(e.target.value)} />
      <SlowList text={deferredText} />
    </>
  );
}

This does not make re-rendering of the SlowList faster. However, it tells React that re-rendering the list can be deprioritized so that it doesn't block the keystrokes. The list will "lag behind" the input and then "catch up". Like before, React will attempt to update the list as soon as possible, but will not block the user from typing.

Deferred re-rendering of the list

In this example, each item in the SlowList component is artificially slowed down so that you can see how useDeferredValue lets you keep the input responsive. Type into the input and notice that typing feels snappy while the list "lags behind" it.

import { useState, useDeferredValue } from 'react';
import SlowList from './SlowList.js';

export default function App() {
  const [text, setText] = useState('');
  const deferredText = useDeferredValue(text);
  return (
    <>
      <input value={text} onChange={e => setText(e.target.value)} />
      <SlowList text={deferredText} />
    </>
  );
}

```js {expectedErrors: {'react-compiler': [19, 20]}} src/SlowList.js import { memo } from 'react';

const SlowList = memo(function SlowList({ text }) { // Log once. The actual slowdown is inside SlowItem. console.log('[ARTIFICIALLY SLOW] Rendering 250 ');

let items = []; for (let i = 0; i < 250; i++) { items.push(); } return (

    {items}
); });

function SlowItem({ text }) { let startTime = performance.now(); while (performance.now() - startTime < 1) { // Do nothing for 1 ms per item to emulate extremely slow code }

return (

  • Text: {text}
  • ) }

    export default SlowList;

    
    ```css
    .items {
      padding: 0;
      max-height: 300px;
      overflow: auto;
    }
    
    .item {
      list-style: none;
      display: block;
      height: 40px;
      padding: 5px;
      margin-top: 10px;
      border-radius: 4px;
      border: 1px solid #aaa;
    }
    

    Unoptimized re-rendering of the list

    In this example, each item in the SlowList component is artificially slowed down, but there is no useDeferredValue.

    Notice how typing into the input feels very janky. This is because without useDeferredValue, each keystroke forces the entire list to re-render immediately in a non-interruptible way.

    import { useState } from 'react';
    import SlowList from './SlowList.js';
    
    export default function App() {
      const [text, setText] = useState('');
      return (
        <>
          <input value={text} onChange={e => setText(e.target.value)} />
          <SlowList text={text} />
        </>
      );
    }
    

    ```js {expectedErrors: {'react-compiler': [19, 20]}} src/SlowList.js import { memo } from 'react';

    const SlowList = memo(function SlowList({ text }) { // Log once. The actual slowdown is inside SlowItem. console.log('[ARTIFICIALLY SLOW] Rendering 250 ');

    let items = []; for (let i = 0; i < 250; i++) { items.push(); } return (

      {items}
    ); });

    function SlowItem({ text }) { let startTime = performance.now(); while (performance.now() - startTime < 1) { // Do nothing for 1 ms per item to emulate extremely slow code }

    return (

  • Text: {text}
  • ) }

    export default SlowList;

    
    ```css
    .items {
      padding: 0;
      max-height: 300px;
      overflow: auto;
    }
    
    .item {
      list-style: none;
      display: block;
      height: 40px;
      padding: 5px;
      margin-top: 10px;
      border-radius: 4px;
      border: 1px solid #aaa;
    }
    

    [!WARNING]

    This optimization requires SlowList to be wrapped in memo. This is because whenever the text changes, React needs to be able to re-render the parent component quickly. During that re-render, deferredText still has its previous value, so SlowList is able to skip re-rendering (its props have not changed). Without memo, it would have to re-render anyway, defeating the point of the optimization.

    [!INFO]

    How is deferring a value different from debouncing and throttling?

    There are two common optimization techniques you might have used before in this scenario:

    • Debouncing means you'd wait for the user to stop typing (e.g. for a second) before updating the list.
    • Throttling means you'd update the list every once in a while (e.g. at most once a second).

    While these techniques are helpful in some cases, useDeferredValue is better suited to optimizing rendering because it is deeply integrated with React itself and adapts to the user's device.

    Unlike debouncing or throttling, it doesn't require choosing any fixed delay. If the user's device is fast (e.g. powerful laptop), the deferred re-render would happen almost immediately and wouldn't be noticeable. If the user's device is slow, the list would "lag behind" the input proportionally to how slow the device is.

    Also, unlike with debouncing or throttling, deferred re-renders done by useDeferredValue are interruptible by default. This means that if React is in the middle of re-rendering a large list, but the user makes another keystroke, React will abandon that re-render, handle the keystroke, and then start rendering in the background again. By contrast, debouncing and throttling still produce a janky experience because they're blocking: they merely postpone the moment when rendering blocks the keystroke.

    If the work you're optimizing doesn't happen during rendering, debouncing and throttling are still useful. For example, they can let you fire fewer network requests. You can also use these techniques together.


    Sitemap

    Overview of all docs pages