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.

When a component mounts, React inserts its elements into the DOM for the first time. When it unmounts, React removes those elements from the DOM permanently.

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 the usersAtom as shown below:

atoms/user.ts
import { Effect } from "effect";
import { Atom } from "effect/unstable/reactivity";
import { atomRuntime } from "@/atom-runtime";
import { UserService } from "@/services/user-service";
// ============ Users Atom ============
export const usersAtom = atomRuntime
.atom(
Effect.gen(function* () {
const userService = yield* UserService;
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.

Last updated on March 6, 2026

Sign in to save progress

Stay in the loop

Get notified when new Effect Atom related content is published.