Use SWR Librery For Data Fetching In React App.
- Published on
Use SWR Librery For Data Fetching In React App
The fetching process in the context of web development refers to the process of getting data from a server.
The process in web development usually starts when a client-side application, such as a web browser or a mobile app, sends a request to a server to fetch data from there. This request is usually made using HTTP methods such as GET
, POST
, PUT
, DELETE
, etc.
Using SWR
In this section, we'll speak about how to fetch data from a server using SWR on ReactJS library on the client-side. Full name is "Stale-While-Revalidate." It's a React Hooks library for data fetching developed by Vercel . SWR focuses on providing a great user experience by automatically managing data fetching, caching, and revalidating data when needed.
Instal SWR librery
npm i swr
Define the Component
Define the SwrFetching component. This component uses the swrFetching hook to fetch data.
export const SwrFetching = () => {
// Destructure the values returned by the swrFetching hook
const { data, isLoading, isError } = swrFetching(1);
// Render different components based on statuses
if (isError) return <div>Failed Load Data</div>;
if (isLoading) return <div>Loading ...</div>;
// Render the fetched data
return (
<>
{data.title}
</>
)};
Define the custom hook
The custom hook swrFetching utilizes useSWR from the SWR library to fetch data.
// Define a fetcher function to fetch data from an API
const fetcher = (...args) => fetch(...args).then((res) => res.json());
// Define the custom hook
const SwrFetching = (id) => {
// Use the useSWR hook to fetch data
const { data, error, isLoading } = useSWR(
`https://jsonplaceholder.typicode.com/posts/1${id}`,
fetcher
);
// Return the loading state, error, and fetched data
return { isLoading, error, data };
};
export default SwrFetching;
Some key features.
Automatic Cashing:
- Automatically caches data fetched from the server in memory, which helps in reducing unnecessary network requests and improves performance
Stale-While-Revalidate Strategy:
- Data from the cache (if available) is providing a fast response to the UI. Then, it validates the data in the background, updating the cache with fresh data. This provide that the UI is always responsive and up-to-date with the latest data.
Error Handling:
- Allows to easily handle different error statuses in application.
Integration with React Hooks:
- SWR is built using React Hooks, making it easy to integrate with React functional components.
SWR does a simple process by providing a higher-level abstraction correctly designed for handling data fetching, caching, and real-time updates in React applications. It can save you time and effort, and provide a clear user experience compared to manually managing data fetching with lower-level libraries like Axios or Fetch.
So when we can use SWR data fetching process
- Real-Time Data Updates
Think about that we are building a live chat application where messages are continually being added and updated. SWR would be a great choice here because it automatically revalidates data in the background, ensuring that users always see the latest messages without having to manually refresh the page.
- Dashboard with Real-Time Analytics
When creating a dashboard that displays real-time analytics data, such as website traffic or sales figures also we can think about SWR.
- Social Media Feeds
Applications where users' social media feeds are continuously updated with new posts, notifications or images.
There are several methods for fetching data in ReactJS, including using built-in browser APIs like fetch() or third-party libraries like Axios. These methods enable developers to initiate HTTP requests and handle the resulting responses asynchronously.Will speak about other methods in the future subscribe me and follow me on social media.