Home > Web Front-end > JS Tutorial > Cache your fetcher in useSWR with useCallback.

Cache your fetcher in useSWR with useCallback.

王林
Release: 2024-07-30 06:43:03
Original
993 people have browsed it

I found a way that caches the fetcher in useSWR using useCallback in the Gitroom source code.

Cache your fetcher in useSWR with useCallback.

The above image is from platform-analytics/render.analytics.tsx. Let’s try to understand this code snippet.

we’ll explore how to optimize data fetching in your React applications using the useCallback hook in combination with useSWR. We'll break down the provided code snippet, explain why caching your fetcher function is important.

Understanding the Code

Let’s dive into the code step by step:

const load = useCallback(async () => {
  setLoading(true);
  const load = (
    await fetch(\`/analytics/${integration.id}?date=${date}\`)
  ).json();
  setLoading(false);
  return load;
}, \[integration, date\]);
Copy after login

Here, we’re defining an asynchronous function load inside a useCallback hook. This function fetches data from a specified endpoint and handles the loading state. The useCallback hook ensures that this function is memoized and only recreated when the dependencies (integration and date) change.

Next, we use useSWR to manage the data fetching:

const { data } = useSWR(\`/analytics-${integration?.id}-${date}\`, load, {
  refreshInterval: 0,
  refreshWhenHidden: false,
  revalidateOnFocus: false,
  revalidateOnReconnect: false,
  revalidateIfStale: false,
  refreshWhenOffline: false,
  revalidateOnMount: true,
});
Copy after login

Here, useSWR is configured with a key (/analytics-${integration?.id}-${date}) and our memoized load function. The configuration options control the revalidation behavior of the data.

How useCallback Prevents Unnecessary Re-fetches

To understand how useCallback prevents unnecessary re-fetches, we need to delve into how React handles function references and how useSWR works.

Function References in React

In React, every time a component re-renders, all functions defined within it are recreated. This means that without useCallback, a new instance of your load function would be created on every render.

Cache your fetcher in useSWR with useCallback.

Impact on useSWR

useSWR is a data fetching library for React. It uses a key to identify the data and a fetcher function to fetch it. useSWR relies on the stability of the fetcher function reference. If the reference changes, useSWR might interpret this as a signal that the data needs to be refetched, even if the actual logic of the fetcher hasn't changed.

Here’s a detailed explanation:

  1. Without useCallback:
const load = async () => {
  setLoading(true);
  const load = (
    await fetch(\`/analytics/${integration.id}?date=${date}\`)
  ).json();
  setLoading(false);
  return load;
};

const { data } = useSWR(\`/analytics-${integration?.id}-${date}\`, load, {
  refreshInterval: 0,
  refreshWhenHidden: false,
  revalidateOnFocus: false,
  revalidateOnReconnect: false,
  revalidateIfStale: false,
  refreshWhenOffline: false,
  revalidateOnMount: true,
});
Copy after login

In this case, every render creates a new load function. useSWR sees a different function reference each time, which can lead to unnecessary re-fetches even when integration and date haven't changed.

With useCallback:

const load = useCallback(async () => {
  setLoading(true);
  const load = (
    await fetch(\`/analytics/${integration.id}?date=${date}\`)
  ).json();
  setLoading(false);
  return load;
}, \[integration, date\]);

const { data } = useSWR(\`/analytics-${integration?.id}-${date}\`, load, {
  refreshInterval: 0,
  refreshWhenHidden: false,
  revalidateOnFocus: false,
  revalidateOnReconnect: false,
  revalidateIfStale: false,
  refreshWhenOffline: false,
  revalidateOnMount: true,
});
Copy after login

By wrapping the load function in useCallback, we ensure that it is only recreated when its dependencies (integration and date) change. This stability in the function reference tells useSWR that the fetcher function hasn't changed unless integration or date changes, thus preventing unnecessary re-fetches.

Want to learn how to build shadcn-ui/ui from scratch? Check out build-from-scratch

About me:

Website: https://ramunarasinga.com/

Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/

Github: https://github.com/Ramu-Narasinga

Email: ramu.narasinga@gmail.com

Build shadcn-ui/ui from scratch

References:

  1. https://github.com/gitroomhq/gitroom/blob/c03b96215fa30b267a97d7eafc2281f482a3192f/apps/frontend/src/components/platform-analytics/render.analytics.tsx#L25
  2. https://github.com/search?q=repo%3Agitroomhq%2Fgitroom%20useSWR&type=code
  3. https://swr.vercel.app/docs/getting-started
  4. https://react.dev/reference/react/useCallback

The above is the detailed content of Cache your fetcher in useSWR with useCallback.. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template