author avatar

ayasha.pandey

Thu Sep 26 2024

Swr: Stale-While-Revalidate is a popular strategy that first returns the data from stale(cache), then send the fetch request (revalidate), and finally come with the up-to-date data.

Why swr? Instant Loading (Faster User Experience) Background Revalidation of the data Improves Offline/Slow Network Experience

We have two most common hooks from SWR data-fetching library to implement swr in our React/Next application -

  1. useSWR - with useSWR we can easily fetch data from an API or any source. The hook automatically handles everything like caching, revalidation, error handling, and cache data updates. For example, it revalidates the data when component mounts, when the user refocuses the browser tab, reconnects to the internet, or on custom revalidation interval.
import useSWR from 'swr';

// Fetcher function
const fetcher = (url) => fetch(url).then((res) => res.json());

function MyComponent() {
  const { data, error, isLoading } = useSWR('<https://api.example.com/data>', fetcher);

  if (error) return &lt;div&gt;Error loading data&lt;/div&gt;;
  if (isLoading) return &lt;div&gt;Loading...&lt;/div&gt;;

  return &lt;div&gt;{JSON.stringify(data)}&lt;/div&gt;;
}
  1. useSWRMutation - It complements useSWR by providing a way to modify data, such as performing create, update, or delete operations. While useSWR is designed for reading data and displaying it in your app, useSWRMutation focuses on mutating or updating that data on the server side.
import useSWRMutation from 'swr/mutation';

// Function to update data
const updateData = (url, { arg }) =&gt;
  fetch(url, {
    method: 'PUT',
    body: JSON.stringify(arg),
    headers: { 'Content-Type': 'application/json' },
  });

function MyMutationComponent() {
  const { trigger, isMutating } = useSWRMutation('<https://api.example.com/data>', updateData);

  const handleUpdate = async () =&gt; {
    await trigger({ id: 1, name: 'New Name' });
  };

  return (
    &lt;div&gt;
      &lt;button onClick={handleUpdate} disabled={isMutating}&gt;
        Update Item
      &lt;/button&gt;
      {isMutating &amp;&amp; &lt;span&gt;Updating...&lt;/span&gt;}
    &lt;/div&gt;
  );
}

#swr #hook #react #next