Simple Data Fetching
With React Query
Daniel Mocan
Software Developer
Meetup organizer
@danielsmocan
Classic Data Fetching
import React, {useEffect, useState} from 'react';
import apiService from '../utils/apiService';
const Products = () => {
const [ products, setProducts] = useState();
const [ isLoading, setLoading] = useState(true);
useEffect(() => {
const getProducts = async () => {
const products = await apiService.getProducts();
if(products){
setProducts(products)
}
setLoading(false);
}
getProducts();
},[]);
return (
<div>
<h2>Products</h2>
{isLoading && <div>...loading</div>}
{ products && products.map( product => <div>{product.productName}</div>)}
</div>
)
};
With React Query
import React from 'react';
import { useQuery } from 'react-query';
import apiService from '../utils/apiService';
const ProductsRQ = () => {
const { data: products, isLoading } = useQuery('products', apiService.getProducts);
return (
<div>
<h2>RQ Products</h2>
{ isLoading && <div>...loading</div> }
{ products && products.map( product => <div>{ product.productName }</div>)}
</div>
)
};
Easy Setup
import { QueryClientProvider, QueryClient } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
const queryClient = new QueryClient();
const App => () => {
return (
<QueryClientProvider client={queryClient}>
<div>
App Components
</div>
<ReactQueryDevtools initialIsOpen={false} position='bottom-right' />
</QueryClientProvider>
)
};
export default App;
What is React Query?
fetch
cache
synchronize and update
Client State & Server State
Client State
Server State
React Query's Goal
Client State
Server State
React Query
Why I Like React Query
import React, {useState} from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import apiService from '../utils/apiService';
const ProductsRQ = () => {
const { data: products, isLoading } = useQuery('products', apiService.getProducts);
const [ product, setProduct] = useState();
const queryClient = useQueryClient() // gets the current client instance
const { mutate } = useMutation(apiService.addProduct, {
onSuccess: () => {
queryClient.invalidateQueries('products')
},
});
const addProduct = () => mutate(product);
//......
};
export default ProductsRQ;
Mutation Data Invalidation
DevTools
Why I Like React Query
less code
tries
widely used
lots of features out of the box
More
Why I Like React Query
"agressive and sane defaults"
deduping
Thank you