[]previous and next page

cache

Memoizes fn per request: within one root (a server render, or the app on the client) the same arguments return the same result without calling fn again.

Memoizes fn per request: within one root (a server render, or the app on the client) the same arguments return the same result without calling fn again. Arguments compare with Object.is, position by position. Results are kept in a list bounded by limit; the oldest is dropped first. A call that throws is not kept. Outside any owner nothing is scoped, so fn runs every time.

Use it to share one data fetch between components rendered in the same request.

Import#

ts
import { cache } from "@shadow-js/core";

Signature#

ts
function cache<A extends unknown[], R>(
  fn: (...args: A) => R,
  options?: CacheOptions,
): (...args: A) => R

Parameters#

Name Description
fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.
options Per-scope limit. Undefined uses the default.

Returns#

A function with the same signature.

Throws#

  • RangeError when limit is not a positive integer (message code SHADOW_CACHE_LIMIT in production builds). The returned function rethrows what fn throws.

Examples#

ts
import { cache } from "@shadow-js/core";

const loadUser = cache((id: string) =>
  fetch(`/api/users/${id}`).then((response) => response.json()),
);
// Two components calling loadUser("u1") in the same render fetch once.