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).
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.
To see this in action, go to the home page. Then click the Add User link to navigate away. Now return to the home page. Notice the spinner appears 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:
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);