Member-only story

React Query Basic Usage

Vinodh Thangavel
2 min readJul 4, 2023

--

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…

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet