What is `select` in React Query?
mainThe select option in useQuery (and useSuspenseQuery) allows you to pick, transform, or compute derived state from the data returned by your queryFn.
Instead of subscribing a component to the entire query result, select enables fine-grained subscriptions. A component using select will only re-render if the specific value returned by the select function changes. This is highly effective for optimizing performance when an endpoint returns large objects where only a few fields are needed by a specific component, or when some fields change frequently while others change rarely.
// Example: Selecting only the title to prevent re-renders when other product fields change
function ProductTitle({ id }: Props) {
const productTitleQuery = useSuspenseQuery({
...productOptions(id),
select: (data) => data.title,
})
return <h1>{productTitleQuery.data}</h1>
}