DEV Community

Khushi Patel
Khushi Patel

Posted on

React Data Fetching Made Easy: SWR to the Rescue 🚨

Ever felt like getting data from an API is like trying to get a cat to take a bath?

cat bath

Frustrating, right? But don’t worryβ€”there’s a simple way to make this whole process smooth and easy.

Let me introduce you to SWR and useSWR, two tools that make fetching data in React a breeze.

What is SWR? πŸ€”
SWR stands for Stale-While-Revalidate. Sounds fancy, but it’s really just a smart way to fetch data. Here’s how it works:

Imagine you’re waiting for a pizza delivery. You’re super hungry, so you want it fast. But you also want it fresh, right? SWR makes sure you get your pizza (data) quickly by giving you the last slice you had while it goes and gets a new, hot one in the background.
If the new slice is ready, SWR swaps it out for you. So, you’re never left waiting, and you always get the freshest slice.

What’s useSWR? πŸ•
useSWR is a special tool (a hook) in React that lets you use SWR in your app. It’s like speed-dialing the pizza place to order your favorite slice without any hassle.

A Simple Example with Cats😺
Let’s say you’re building an app that shows random cat facts (because cats are awesome). You have an API that gives you these facts, and you want to display them in your app. Here’s how you can do it with useSWR.



import useSWR from 'swr';

// This is the fetcher function that goes to the API to get data.
const fetcher = (...args) => fetch(...args).then(res => res.json());

export default function CatFact() {
  // useSWR calls the API and returns data, error, and loading state.
  const { data, error } = useSWR('https://catfact.ninja/fact', fetcher);

  if (error) return <div>Oops! Something went wrong. Try again.</div>;
  if (!data) return <div>Loading your cat fact...</div>;

  // If all is good, show the cat fact.
  return <div>🐱 Did you know? {data.fact}</div>;
}


Enter fullscreen mode Exit fullscreen mode

What’s Happening Here?
Fetcher Function: This function is like the delivery guy who gets your pizza. It fetches data from the API and brings it back to your app.

useSWR: This hook is where the magic happens. You give it the API URL (where the cat facts live) and the fetcher function, and useSWR handles the rest. It takes care of getting the data, showing it in your app, and even updating it if new data comes in.

Handling Errors and Loading: If something goes wrong (the pizza guy gets lost), we show an error message. If the data is still being fetched (pizza is on its way), we show a loading message. Once the data is ready, we display the cat fact.

Why Use SWR? πŸ€·β€β™€οΈ
SWR makes fetching data in React super easy. It’s fast, keeps your app up-to-date, and you don’t have to worry about stale (old) data. So, next time you’re working on a React app and need to get data from an API, try using SWR and useSWR. It’ll make your life a lot easier, just like having pizza delivered right to your door!

Happy coding! πŸŽ‰

Top comments (3)

Collapse
 
femil profile image
Femil Savaliya

Awesome πŸ”₯

I have one doubt: if I have to call the same API on multiple pages but I don't want to call the API or just want the cache data, is it possible to revalidate after a difficult time?

cats are really awesome 😊

Collapse
 
aditya_parmar profile image
Aditya Parmar • Edited

Yes, You can
let's take below example

Image description

In above example if you want:

1)Caching then: use the same key for multiple pages
By using the same key (/api/cats) across multiple pages, the data will be cached and shared between them automatically

2)Revalidatoin then : SWR offers several configuration options to control when data should be revalidated

  • revalidateOnFocus: Controls whether the data should be revalidated when the user focuses on the window.

  • refreshInterval: Allows setting an interval to automatically revalidate the data at specified intervals.

  • dedupingInterval: Specifies a time period (in milliseconds) within which duplicate requests are ignored.

Collapse
 
hanzla-baig profile image
Hanzla Baig

πŸ‘