Persistent localStorage cache with SWR
Joshua Rodriguez
Posted on January 22, 2023
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));
});
};
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();
...
💖 💪 🙅 🚩
Joshua Rodriguez
Posted on January 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
privacy Caught in the Crunch My Journey from Snacks to 2 Million Exposed Users Privacy
November 30, 2024
devchallenge Submission for the DevCycle Feature Flag Challenge: Feature Flag Funhouse
November 30, 2024