Member-only story
React Query Basic Usage
React Query is often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronizing and updating server state — Tanstack Documentation
A typical API call with fetch in react library can be done with following snippet
export default function App() {
const [data, setData] = useState();
const [error, setError] = useState();
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
setIsLoading(true);
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => {
return response.json();
})
.then((data) => {
setIsLoading(false);
setData(data);
})
.catch((error) => {
setIsLoading(false);
setError(error);
});
}, []);
if (isLoading) {
return <div> Loading</div>;
}
if (error) {
return <p>Error {error.message} </p>
}
return (
<div>
<h1>{data?.title}</h1>
</div>
);
}
We can built a custom hook, which can help reusing some of these across components.
React Query on the other hand helps with lot of useful hooks that makes fetching, caching, synchronizing and update server state very easily
import { useQuery } from 'react-query';
export default function App() {
const { data, error, isLoading } = useQuery('todo', () =>
fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) => {
return response.json();
})
);
if…