Keeping Atoms Alive

Avatar of Hemanta SundarayHemanta Sundaray

When an effectful Atom runs its Effect, the Registry caches the returned value. Any component that reads the Atom afterward gets the cached value instantly, without re-running the Effect.

However, this cache only lives as long as at least one component subscribed to the Atom remains mounted. When every component that reads the Atom unmounts, the Registry discards the cache (after a short grace period of 400ms).

Note

A component is subscribed to an Atom when it uses a hook such as useAtomValue to read the Atom’s value. The subscription starts when the component mounts and ends when it unmounts.

What happened? When you navigated away, the UserGrid component unmounted. Since no other components were subscribed to usersAtom, the Registry discarded its cache. When you navigated back, UserGrid mounted again, but the cache was empty, so the Atom had to run its Effect again.

This default behavior makes sense for many scenarios. But in our case, the users’ data doesn’t change frequently. Why fetch the same data and show a spinner every time the home page loads?

Instead, we can persist the cache using Atom.keepAlive.

Update atoms/user.ts as shown below:

atoms/user.ts
import { Atom } from "@effect-atom/atom-react";
import { Effect } from "effect";
import { atomRuntime } from "@/atom-runtime";
import { UserService } from "@/services/user-service";
// ============ Users Atom ============
export const usersAtom = atomRuntime
.atom(
Effect.gen(function* () {
return yield* UserService.getUsers();
}),
)
.pipe(Atom.keepAlive);

Now navigate away from the home page and return. The spinner no longer appears. The data is served instantly from cache.

Sign in to save progress

Stay in the loop

Get notified when new chapters are added and when this course is complete.