DEV Community

Joshua Rodriguez
Joshua Rodriguez

Posted on

Persistent localStorage cache with SWR

None of the current tutorials on the web actually worked for me, after some hours of investigation I created this hook

The only dependencies are "usehooks-ts" (just for commodity) and "swr" itself

import { useLocalStorage, useEventListener } from "usehooks-ts";
import { useSWRConfig } from "swr";
import { useEffect } from "react";

export const useSWRCache = () => {
  const [swrCache, setSWRCache] = useLocalStorage("swrcache", "{}");
  const parsedSWRCache = JSON.parse(swrCache) as object;
  const { cache, mutate } = useSWRConfig();

  useEffect(() => {
    Object.entries(parsedSWRCache).forEach(([key, value]) => {
      if (!value) return;
      cache.set(key, value);
    });

    // @ts-ignore
    for (const key of cache.keys()) {
      mutate(key);
    }
  });

  useEventListener("beforeunload", () => {
    const newCache: any = {};

    // @ts-ignore
    for (const key of cache.keys()) {
      newCache[key] = cache.get(key);
    }

    setSWRCache(JSON.stringify(newCache));
  });
};
Enter fullscreen mode Exit fullscreen mode

This will save the cache on the localStorage when the "beforeunload" event is triggered (every time an user closes the tab, or reloads the page)

And then it will reload the cached keys from the localStorage once the page is loaded with useEffect

To use it you only need to place it in the main App.tsx or _app.tsx (Next.js) components

Like this:

function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
  useSWRCache();

...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)