Blog>
Snippets

Correctly Structuring Query Keys to Avoid Over-fetching

This code snippet demonstrates the importance of properly structuring query keys to avoid over-fetching data, showcasing best practices for query key design.
const fetchPosts = async (userId) => {
  const response = await fetch(`/api/posts?userId=${userId}`);
  return response.json();
};
Defines an async function to fetch posts for a specific user from an API.
const { data, isLoading } = useQuery(['posts', userId], () => fetchPosts(userId), {
  enabled: !!userId
});
Uses React Query's useQuery hook to fetch data. The query key is structured as an array with 'posts' and a dynamic userId to uniquely identify the query. This structure helps in avoiding over-fetching by ensuring the data is fetched only when the userId is available.
// Component usage
if (isLoading) return <div>Loading...</div>;
return (
  <ul>
    {data.map(post => (
      <li key={post.id}>{post.title}</li>
    ))}
  </ul>
);
Renders the fetched data. Show a loading state while the data is being fetched, then renders the posts in a list. This demonstrates the component usage of the structured query key.