Fetching data in React often means using stale state and complex caching logic.

React Query simplifies data fetching with powerful features like automatic caching, deduplication, and background updates.

Let’s explore some key features of React Query:

Declarative Data Fetching

Fetch data with the useQuery hook:

1
2
3
4
5
6
7
import { useQuery } from 'react-query';

function MyComponent() {
  const { data, error, isLoading } = useQuery('posts', fetchPosts);
  
  // use data  
}

useQuery handles declaring cache keys, performing fetches, and more.

background Refetching

React Query automatically refetches “inactive” queries in the background:

1
2
3
4
5
// frontend
useQuery('user', fetchUser); 

// background
// periodically refetches user

Stale data is updated without blocking the UI.

Request Deduplication

Duplicate requests are deduped to prevent wasteful refetches:

1
2
3
4
5
6
7
function PageOne() {
  useQuery('posts', fetchPosts);
}

function PageTwo() {
  useQuery('posts', fetchPosts); // not duplicated
}

React Query shares cache results across components.

Optimistic Updates

Mutations can update the cache optimistically before fetching:

1
2
3
4
5
6
7
8
const mutation = useMutation(addPost, {
  onMutate: newPost => {
    // update cache immediately 
  },
  onError: (err, newPost, context) => {
    // rollback optimistic update 
  },
});

This makes the UI feel fast and responsive.

Summary

  • Simplifies data fetching with useQuery
  • Refetches stale data in background
  • Deduplicates requests automatically
  • Optimistic updates make UI feel snappy

React Query takes the pain out of async data management!