Daniel Mocan

Engineering Manager

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>
    )
};

React Query

import React from 'react';
import { useQuery } from '@tanstack/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>
    )
};

With...

Easy Setup

import { QueryClientProvider, QueryClient } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/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

Client State

Server 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 '@tanstack/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

retries

widely used

lots of  features out of the box

Even More

Why I Like React Query

"agressive and sane defaults"

deduping

¡Gracias!

Made with Slides.com