React Cache:关键在于一致性

If you've spent any time with data fetching and React Server Components, you've probably reached for React's cache function a handful of times.

如果你曾花时间处理数据获取和 React Server Components,你可能已经多次使用过 React 的 cache 函数。

In this post, I want to make the case for appreciating cache as more than just a memoization and optimization technique for network data fetching, but instead as an API that guarantees consistency across an entire RSC render.

在这篇文章中,我想论证 cache 不仅仅是一种用于网络数据获取的记忆化和优化技术,而是一种能够在整个 RSC 渲染过程中保证一致性的 API。

But first, let's look at one of the most common ways cache is used today.

但首先,让我们看看今天cache最常见的用法之一。

Deduplicating data fetches

去重数据获取

React's cache is often used to deduplicate requests made by multiple components that need access to the same external data.

React 的 cache 常用于去重,避免多个组件在需要相同外部数据时重复发起请求。

Here's an example of two components that both need the source HTML of react.dev's homepage:

下面是一个示例,两个组件都需要 react.dev 首页的源 HTML:

import { cache } from "react";

export default function Page() {
 return (
 <div>
 <ReactsPageTitle />
 <ReactsPageDescription />
 </div>
 );
}

async function ReactsPageTitle() {
 const reactsHtml = await getPage("https://react.dev");
 const title = reactsHtml.match(/<title>(.*?)<\/title>/)[1];
 return (
 <div>
 <p>Page title: {title}</p>
 </div>
 );
}

async function ReactsPageDescription() {
 const reactsHtml = await getPage("https://react.dev");
 const description = reactsHtml.match(
 /<meta name="description" content="(.*?)"/,
 )[1];
 return (
 <div>
 <p>Page description: {description}</p>
 </div>
 );
}

const getPage = cache(async (url) => {
 const res = await fetch(url);
 const html = await res.text();
 return html;
});

This is where cache really shines. Both <ReactsPageTitle> and <ReactsPageDescription> need the same data, but rather than hoist the fetch up to the parent component and pass it down as a prop, we use cache to ensure that only one fetch is made and shared between the two components. This lets each component have local data fetching without worrying about duplicated requ...

开通本站会员,查看完整译文。

Home - Wiki
Copyright © 2011-2025 iteam. Current version is 2.146.0. UTC+08:00, 2025-08-28 21:52
浙ICP备14020137号-1 $Map of visitor$