right way to clear SWR cache

958 Views Asked by At

SWR recommends using

mutate(
  key => true, // which cache keys are updated
  undefined, // update cache data to `undefined`
  { revalidate: false } // do not revalidate
)

to clear cache. And I can not decide between

import {mutate} from "swr"

and

const {mutate} = useSWRConfig()

which is better in this case ?

1

There are 1 best solutions below

0
On

Clearing the cache using SWR, both methods achieve the same result, and the choice between them depends on your preference and usage pattern.

via mutate from swr directly

import { mutate } from 'swr';

mutate(
  key => true, // which cache keys are updated
  undefined,   // update cache data to `undefined`
  { revalidate: false } // do not revalidate
);

via mutate from useSWRConfig

import { useSWRConfig } from 'swr';

const { mutate } = useSWRConfig();

mutate(
  key => true, // which cache keys are updated
  undefined,   // update cache data to `undefined`
  { revalidate: false } // do not revalidate
);

The primary difference is the source of the mutate function just

Direct Import import { mutate } from 'swr'

Pros- More concise, especially if you only need the mutate function. Cons- Adds an extra import.

with useSWRConfig hook (const { mutate } = useSWRConfig())

Pros- Integrates with the hook-based pattern of SWR. would be useful if you are already using useSWRConfig for other purposes in your application Cons- Slightly longer syntax. so i would recommend Choosing the one that fits better with the overall structure and style of your code. If you are not using the useSWRConfig hook elsewhere in your application, the direct import might be more straightforward. If you are already using the hook, it might make sense to stick with it for consistency.