📅  最后修改于: 2023-12-03 15:34:40.120000             🧑  作者: Mango
React-query and SWR are two popular libraries that help in fetching and caching data in React applications. Both of them promise to make data fetching easier and more efficient. This article aims to compare and contrast the features of these libraries to help developers understand which one to choose for their specific use case.
React-query is a library developed by Tanner Linsley, which provides a declarative way of fetching, caching, and updating asynchronous data in React applications. It comes with built-in support for many features such as automatic query retries, cache updates, and optimistic updates.
SWR is a library developed by Vercel, which stands for "stale-while-revalidate". It provides a simple API for fetching and caching data in real-time from APIs, with a focus on performance and ease-of-use.
If you require a declarative way of fetching data, with built-in support for cache and other advanced features, then react-query is the right choice. React-query is suited for complex applications that require caching and real-time updates, such as e-commerce websites, dashboard applications, and social media platforms.
If you require a simpler way of fetching data, with focus on performance and simplicity, then SWR is a good fit. SWR is suited for applications that require real-time updates, but not heavy caching, such as blogs, news websites, and static websites.
import { useQuery } from 'react-query';
function App() {
const { isLoading, data, error } = useQuery('todos', () =>
fetch('https://jsonplaceholder.typicode.com/todos').then((res) =>
res.json()
)
);
if (isLoading) return 'Loading...';
if (error) return `Error: ${error.message}`;
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
}
import useSWR from 'swr';
function App() {
const { data, error } = useSWR(
'https://jsonplaceholder.typicode.com/todos'
);
if (error) return `Error: ${error}`;
if (!data) return 'Loading...';
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
}
React-query and SWR are both excellent libraries for fetching and caching data in React applications. React-query provides a more declarative way of working with data, with built-in support for caching and other features. SWR, on the other hand, provides a simpler API, with focus on performance and ease-of-use.
Ultimately, the choice between react-query and SWR depends on your use case and the specific requirements of your application. If you need advanced data features, caching, and real-time updates, react-query is a good fit. If you need a simpler way of fetching data with emphasis on performance, then SWR is a good choice.