For example, I switch to different page using react router:
const Apage = () => {
const { data, error } = useSWR('/a-data', fetcher);
return (
<div>{data}</div>
);
};
const Bpage = () => {
const { data, error } = useSWR('/b-data', fetcher);
return (
<div>{data}</div>
);
};
With swr, I can get data immediately when I’m not the first time access the page.
But still, it calls the api to fetch data each time I access the page.
Can I only fetch data once if I dont need to revalidate the data is stale or not?
SWR
concept is based onhooks
. That means it means to use with local state, not for global state likemobx
/redux
/etc. Of course you can use with global state viaReact Context
by creating your custom context. But you will prefer to usemobx
/redux
instead right?So this is a caching strategy. If you prefer cache in memory, use
mobx
/redux
. Otherwise, store inlocalStorage
/cookie
/etc.You can set
revalidateOnFocus
tofalse
to prevent SWR from revalidating when the window comes back into view.https://swr.vercel.app/docs/revalidation
Just use dedupingInterval, like:
SWR 0.3.8
You should prevent automatic revalidation which is controlled by the next options:
According to the documentation
refreshWhenOffline
,refreshWhenHidden
andrefreshInterval
are disabled by default, so it’s enough only to set:This will restrict SWR from running the fetching method. However, you still need the first one run to get your data.
You may end up with something like this:
SWR cache is exposed since 0.2.0 version
After all, I do not recommend using SWR for this purpose. SWR built to fetch data again. If you have static data – fetch once and store in session/local storage or define your own cache.