Blog>
Snippets

Optimizing Component Re-renders with `notifyOnChangeProps`

This example demonstrates how to optimize component re-renders by specifying which properties changes should trigger an update, using `notifyOnChangeProps` in React Query options.
import { useQuery } from 'react-query';

function fetchTodos() {
  // Fetch todos from an API
}

export const useTodosQuery = () =>
  useQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
    notifyOnChangeProps: ['data', 'error'],
  });
This snippet demonstrates how to use React Query's `useQuery` hook to fetch todos. It optimizes component re-renders by specifying that components should only re-render when the `data` or `error` properties change. This is achieved by setting `notifyOnChangeProps` to `['data', 'error']`.
export const useTodoCount = () =>
  useTodosQuery({
    select: todos => todos.length,
    notifyOnChangeProps: ['data']
  });
This snippet is an extension of the first example where it demonstrates the use of the `select` option in conjunction with `notifyOnChangeProps`. Here, `useTodoCount` is a custom hook that uses `useTodosQuery` internally but selects only the length of the todos array, causing components to only re-render when the `data` changes (specifically the count of todos), ignoring other changes.
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      notifyOnChangeProps: 'all',
    },
  },
});

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Components using React Query here */}
    </QueryClientProvider>
  );
}
This example demonstrates how to globally opt-out of the smart tracking optimization provided by React Query, by setting `notifyOnChangeProps` to 'all' in the default options of the `QueryClient`. This configuration ensures that any query will trigger re-renders on any updates unless explicitly configured otherwise at the query level.