clear swr cache

Clear SWR Cache

SWR is a React Hooks library for data fetching. It caches the data in the client-side to optimize the performance and reduce the number of requests to the server. Sometimes, we need to clear the SWR cache to get fresh data from the server. There are different ways to clear the SWR cache:

1. Using the `mutate` function

The easiest way to clear the SWR cache is by using the `mutate` function with the `revalidate` option set to `true`. This will invalidate the cache and trigger a revalidation of the data from the server.


import useSWR from 'swr';

const { data, mutate } = useSWR('/api/data');

const handleClearCache = () => {
  mutate(undefined, true);
};

2. Using the `cache.clear` method

The SWR cache object has a `clear` method that can be used to clear the entire cache. This will remove all cached data for all endpoints.


import useSWR, { cache } from 'swr';

const handleClearCache = () => {
  cache.clear();
};

3. Using the `cache.delete` method

The SWR cache object also has a `delete` method that can be used to remove cached data for a specific endpoint.


import useSWR, { cache } from 'swr';

const handleClearCache = () => {
  cache.delete('/api/data');
};

These are the different ways to clear the SWR cache. Depending on your use case, you can choose the one that suits you the best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe