Blog>
Snippets

Implementing Selectors with React Query for Efficient Data Transformation

Explains how to use selectors within React Query to efficiently transform or filter data without causing unnecessary re-renders, preserving application performance.
import { useQuery } from 'react-query';

function fetchTodos() {
  // Example fetch function
  return fetch('https://api.example.com/todos').then(res => res.json());
}

export const useTodos = (select) => {
  return useQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
    select,
  });
};
Defines a custom hook useTodos that fetches todo items and optionally transforms the data using a select function if provided. This allows for filtering or restructuring of the data before it is consumed by the component, reducing the need for additional data processing in the component itself.
export const useFilteredTodos = (filter) => {
  return useTodos(data => data.filter(todo => todo.status === filter));
};
Creates a custom hook useFilteredTodos that uses the useTodos hook with a select function to filter todos by status. Only todos matching the provided filter will be returned, minimizing the need for the consuming component to re-filter the data.
export const useTodoCount = () => {
  return useTodos(data => data.length);
};
Implements a custom hook useTodoCount that uses the useTodos hook with a select function to return the count of todos. This optimizes performance by avoiding re-renders when properties of the todos change that do not affect the count.