Simplifying React: Fetching Data with useSWR

Photo by Lautaro Andreani on Unsplash

Fetching data from databases or external APIs is a fundamental task, not just in React but across every web application. Typically, this involves using JavaScript’s Fetch API alongside standard React hooks like useState and useEffect. However, there is a more elegant solution for managing data in React applications — useSWR.

What is useSWR?

useSWR stands for Stale-While-Revalidate. In simple terms, it loads cached data first for users to interact with while simultaneously fetching the latest data from the backend. This approach preserves a smooth user experience by quickly presenting various pages. It is a React hook that simplifies and optimizes data fetching.

Data Fetching without useSWR

Let’s explore how data fetching can be achieved using standard React hooks before diving into useSWR.

Consider a component called Products, responsible for displaying a list of products on an e-commerce website. We'll employ useState to manage:

  1. Actual data upon successful fetching,
  2. Errors encountered during fetching, and
  3. Loading state during the fetching process
const [productList, setProductList] = useState([]); 
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState();

To retrieve data from a REST API endpoint, an async function called fetchData is created. Inside this function, state variables are updated based on the fetch response or encountered errors.

const fetchData = async () => {
try {
setIsLoading(true);
const response = await fetch("api/products");
const data = await response.json();
setProductList(data.products);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
};

Using useEffect, we invoke fetchData to run when the component mounts.

useEffect(() => {
fetchData();
}, []);

The component is then rendered based on the relevant state variables.

if (isLoading) return <div>Loading...</div>;
if (error) return <div>{error.message}</div>;
return (
<div className="product-container">
{productList.map(item => {
// Render productItem into component.
})}
</div>
);

While functional, this approach requires handling multiple states and involves verbose code for error and loading management.

Data Fetching with useSWR

By leveraging useSWR, we can streamline our code for both enhanced readability and performance.

Implementation

To use useSWR, start by installing it in your React project:

npm install swr

Next, create a fetcher function that acts as a wrapper for the native fetch API:

const fetcher = async url => {
const response = await fetch(url);
return await response.json();
};

Now, let’s see how useSWR simplifies the code:

import useSWR from 'swr';

const Products = () => {
const { data, error, isLoading } = useSWR("api/products", fetcher);

if (isLoading) return <div>Loading...</div>;
if (error) return <div>{error.message}</div>;
return (
<div className="product-container">
{data.map(item => {
// Render productItem into component.
})}
</div>
);
};

With useSWR, the code is more concise and significantly easier to read.

Benefits of useSWR

Apart from its succinct syntax, useSWR offers several advantages:

Automatic Caching and Revalidation

useSWR provides cached data for quicker rendering while simultaneously updating with the latest data in the background. This enhances user interaction as users can engage with cached data while fresh data is fetched.

Built-in Error Handling

By including built-in error states, useSWR eliminates the need for extra error-handling code, contributing to more concise and convenient programming.

Optimized Data Fetching

useSWR optimizes performance by minimizing unnecessary requests, re-renders, or code imports.

Conclusion

In conclusion, transitioning from traditional data fetching methods to leveraging useSWR in React offers a paradigm shift in both code elegance and user experience. The concise syntax, automatic caching with background revalidation, and built-in error handling streamline the development process.

By adopting useSWR, developers can significantly reduce boilerplate code, enhance readability, and optimize performance. Moreover, its adaptability and configurability empower teams to tailor data fetching strategies to suit the specific needs of their applications.

This React hook not only simplifies the handling of data but also enriches the overall user interaction by presenting cached data swiftly while seamlessly updating with the latest information. As React evolves, useSWR stands as a powerful tool to simplify complex data management and elevate the efficiency of modern web applications.