SWR is a React hooks library for data fetching built by vercel (maintainer of Next.js). Enables fast, lightweight, reusuable data fetching with built-in caching and request deduplication handling (stops duplicate requests from being sent).
yarn add swr
or
npm install swr
import axios from "axios";
import useSWR from "swr";
const get = (url) => axios.get(url).then((res) => res.data);
const Greetings = () => {
const { data, error } = useSWR("/api/user/123", get);
if (error) return <div>error</div>;
if (!data) return <div>loading...</div>;
return <div>hello {data.name}!</div>;
};
const useUser = (id) => {
const { data, error } = useSWR(`/api/user/${id}`, get);
return {
user: data,
isLoading: !error && !data,
isError: error,
};
};
const Avatar = ({ id }) => {
const { user, isLoading, isError } = useUser(id);
if (isLoading) return <Spinner />;
if (isError) return <Error />;
return <img src={user.avatar} />;
};
import useSWR from "swr";
const Greetings = () => {
const { data } = useSWR("/api/users", get, {
refreshInterval: 60 * 60 * 24 * 1000, // refetches data every 24 hours
});
return ...
};
import axios from "axios";
import useSWR, { mutate } from "swr";
const updateUser = (user) =>
axios.post("/api/user", user).then((res) => res.data);
const Greetings = () => {
const { data } = useSWR("/api/user", get);
const uppercase = () => {
const newUser = { ...data, name: data.name.toUpperCase() };
mutate("/api/user", newUser, false); // mutate local state without revalidation
mutate("/api/user", updateUser(newUser));
};
return (
<div>
<h1>Hi {data.name}</h1>
<button onClick={}>Uppercase</button>
</div>
);
};
SWR์ ์ ์ฉํด์์๋๋ฐ react-query๋ฅผ ์ฐ๋ค๋ณด๋ react-query๊ฐ ์ฅ์ ์ด ํจ์ฌ ๋์ ๋ ๋ง์ด ๋ค์ด์ค๋๋ผ๊ตฌ์.
๊ทธ๋๋ ์๊ฒฌ์ด ๋ง์ด๋ค ๊ฐ๋ ค์ react-query vs SWR ์ด๋ป๊ฒ ๋ณด์๋์ง ๊ถ๊ธํฉ๋๋ค.