SWR make it easy!!!

SWR make it easy!!!


Technologies are evolving so rapidly, especially when it comes to JavaScript. React.js and Next.js are powerful frontend frameworks that are highly popular. They provide several hooks to make developers’ jobs easier.

SWR is a powerful React hook for data fetching. The name SWR stands for Stale-While-Revalidate. It uses an HTTP cache invalidation strategy as per HTTP RFC 5861. SWR is created by the founding team of Next.js. Its name simply means: stale stands for cached data previously fetched from an API, while refers to the transition period, and revalidate means verifying and updating the cached data to ensure it is up to date with the server.




Let’s discuss how it works

First, it fetches data from an API, stores it in the cache, and displays that data in the UI. While displaying stale data, it automatically sends a request in the background to fetch fresh data. After the cache is updated with the latest data, it re-renders the component to reflect the changes.


Examples

…………….

import useSWR from 'swr'

function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)

  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}
Enter fullscreen mode

Exit fullscreen mode


import useSWR from 'swr';

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

export default function UserProfile({ userId }) {
  const { data, error } = useSWR(`https://jsonplaceholder.typicode.com/users/${userId}`, fetcher);

  if (error) return <div>Failed to load user</div>;
  if (!data) return <div>Loading user...</div>;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>Email: {data.email}</p>
      <p>Phone: {data.phone}</p>
    </div>
  );
}

Enter fullscreen mode

Exit fullscreen mode

Features and advantages of SWR

  • The main feature of SWR is fast, lightweight, and reusable data fetching.
  • The most exciting feature is prefetching data, allowing us to preload data before rendering the component.

Why should we use SWR?

  • Because it saves development time and ensures fresh data without over-fetching.

For more references, check the documentation.




Source link
lol

By stp2y

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.