DEV Community

Saurav Pandey
Saurav Pandey

Posted on

Optimizing React Cache Retention: Microtask Eviction in useResource

Optimizing React Cache Retention: Microtask Eviction in useResource

Managing shared cache in client-side React applications can lead to subtle race conditions. When multiple components mount simultaneously or subscribe to shared data resources, synchronous cache eviction can inadvertently remove controllers before active subscriptions register.

In the latest release of react-hook-lab, we refined the internal cache eviction strategy of the useResource hook. By shifting capacity eviction to an asynchronous microtask scheduled after subscription effects settle, active resource controllers are reliably preserved while unused zero-subscriber entries are cleaned up.


What Changed in useResource?

Previously, useResource executed capacity eviction synchronously during controller creation. If the soft limit of 200 registry entries was reached, creating a new resource could trigger eviction before subscribers attached, risking premature cache invalidation.

With this update:

  • Microtask Scheduling: Eviction runs asynchronously using Promise.resolve().then(...) after subscription setup.
  • Subscriber Awareness: Capacity eviction evaluates subscriber counts after components mount, retaining active resource subscriptions.
  • Zero-Subscriber Target: Only controllers with zero active subscribers are removed when exceeding the soft limit.

Code Examples

1. Basic Resource Fetching

Below is how you can use useResource to fetch and automatically cache resource data:

import React from 'react';
import { useResource } from 'react-hook-lab';

interface UserProfile {
  id: string;
  name: string;
  email: string;
}

export const UserProfileCard = ({ userId }: { userId: string }) => {
  const { data, isLoading, error } = useResource<UserProfile>({
    key: `user-${userId}`,
    fetcher: async () => {
      const response = await fetch(`/api/users/${userId}`);
      if (!response.ok) throw new Error('Failed to fetch user');
      return response.json();
    },
  });

  if (isLoading) return <div>Loading profile...</div>;
  if (error) return <div>Error loading profile: {error.message}</div>;

  return (
    <div>
      <h3>{data?.name}</h3>
      <p>{data?.email}</p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

2. Multi-Component Shared Subscriptions

Because eviction is deferred until subscriptions settle, multiple components referencing the same resource key seamlessly share cached state without eviction conflicts:

import React from 'react';
import { useResource } from 'react-hook-lab';

export const HeaderUserBadge = ({ userId }: { userId: string }) => {
  const { data } = useResource({
    key: `user-${userId}`,
    fetcher: () => fetch(`/api/users/${userId}`).then((res) => res.json()),
  });

  return <span>{data ? `Logged in as ${data.name}` : 'Guest'}</span>;
};
Enter fullscreen mode Exit fullscreen mode

Resources


Buy Me A Coffee

Enjoyed this breakdown? Support my open-source work on Buy Me a Coffee or explore react-hook-lab!

Originally published on my blog. You can read the alternative breakdown here.

Top comments (0)