Blog>
Snippets

Preventing Unnecessary Renders

Illustrate using React Query's `select` option in a query to pick only necessary data, preventing unnecessary component re-renders.
import { useQuery } from 'react-query';
import axios from 'axios';
Importing necessary modules from react-query and axios for data fetching.
function fetchUserData() {
  return axios.get('/api/user/1').then(res => res.data);
}
Function to fetch user data from an API using axios.
function UserDetails() {
  const { data: user } = useQuery('userData', fetchUserData, {
    select: data => ({
      name: data.name,
      email: data.email
    })
  });

  return (
    <div>
      <h1>{user?.name}</h1>
      <p>{user?.email}</p>
    </div>
  );
}
UserDetails React component using the useQuery hook from React Query to fetch data. The select option is used to pick only the 'name' and 'email' from the fetched data, minimizing the component's dependency to changes in the data object, thus preventing unnecessary re-renders.