React-Query v1.0: Unlocking New Possibilities

Get Ready for a Revolution

The highly anticipated React-Query v1.0 has finally arrived, bringing with it a plethora of exciting changes and enhancements.

Query Keys and Functions: Unleashing New Power

The latest version of React-Query introduces more serializable members in the array constructor, allowing for more detailed and insightful queries. Additionally, query functions now accept all query key items, enabling them to act on specific queries where they’re called from.

const queryKey = ['posts', { limit: 10 }];
const { data, error, isLoading } = useQuery(queryKey, async () => {
  const response = await fetch('/api/posts');
  return response.json();
});

This breaking change requires an update to the old method of writing query functions.

useQuery Hook: Streamlined and Efficient

The paginated optional argument has been removed, making way for two new Hooks: usePaginatedQuery and useInfiniteQuery.

import { usePaginatedQuery, useInfiniteQuery } from 'eact-query';

const { data, error, isLoading } = usePaginatedQuery(
  'posts', 
  async ({ pageParam = 0 }) => {
    const response = await fetch(`/api/posts?page=${pageParam}`);
    return response.json();
  }
);

const { data, error, isLoading } = useInfiniteQuery(
  'posts', 
  async ({ pageParam = 0 }) => {
    const response = await fetch(`/api/posts?page=${pageParam}`);
    return response.json();
  }
);

The useQuery Hook still operates as usual, but with new options and methods, such as isFetchingMore, canFetchMore, and fetchMore.

const { data, error, isLoading, isFetchingMore, canFetchMore, fetchMore } = useQuery(
  'posts', 
  async () => {
    const response = await fetch('/api/posts');
    return response.json();
  }
);

queryCache: The Heart of React-Query

The queryCache instance is responsible for managing all state activities, caching, lifecycle, and magic of every query.

It boasts several methods, including:

  • prefetchQuery
  • getQueryData
  • setQueryData
  • refetchQueries
  • removeQueries
  • getQuery
  • isFetching
  • subscribe
  • clear
import { queryCache } from 'eact-query';

queryCache.prefetchQuery('posts', async () => {
  const response = await fetch('/api/posts');
  return response.json();
});

These methods provide unparalleled control and flexibility when working with queries.

react-query-devtools: Unparalleled Insights

The new react-query-devtools enable you to:

  • Monitor query operations
  • View retrieved data
  • Remove queries from cache
  • Refetch queries

With four indicators of query state (Fresh, Fetching, Stale, and Inactive), you’ll have complete visibility into your application’s query landscape.

Learn more about react-query-devtools

What’s Next?

The updates to React-Query are nothing short of remarkable. With the addition of devtools, building and debugging apps has never been easier.

Leave a Reply