Blog>
Snippets

Using `select` to Transform and Cache Only Part of the Data

Showcase the use of the `select` function to transform the data received from a query and cache only the necessary part, reducing memory footprint and improving app performance.
import { useQuery } from 'react-query';

const fetchTodos = async () => {
  const response = await fetch('/todos');
  return response.json();
};

const TodosComponent = () => {
  const { data: todos } = useQuery('todos', fetchTodos, {
    // Transform the data to only cache todo titles
    select: data => data.map(todo => todo.title),
  });

  return (
    <ul>
      {todos?.map((title, index) => (
        <li key={index}>{title}</li>
      ))}
    </ul>
  );
};
This code snippet demonstrates how to use the `select` function with `react-query`'s `useQuery` hook to transform and cache only part of the data fetched from an API. Here, the `fetchTodos` function fetches the entire todos list from '/todos', but through the `select` option in `useQuery`, we transform this data to only cache the titles of the todos. This reduces the memory footprint and improves performance, as the component `TodosComponent` then renders a list of todo titles, avoiding unnecessary data processing and storage.