Why React Query Changed How I Think About State
Before React Query, I managed server state in Redux. Action creators, reducers, selectors, loading booleans, error states — it was exhausting boilerplate for what is fundamentally a cache-synchronization problem.
React Query is opinionated in the best way: server state is fundamentally different from UI state, and it solves the former completely.
Pattern 1: Query Key Factories
The most underrated pattern. Never hardcode query keys.
``ts
// lib/queryKeys.ts
export const projectKeys = {
all: ['projects'] as const,
lists: () => [...projectKeys.all, 'list'] as const,
list: (filters: ProjectFilters) => [...projectKeys.lists(), { filters }] as const,
details: () => [...projectKeys.all, 'detail'] as const,
detail: (id: string) => [...projectKeys.details(), id] as const,
}
`
Now invalidation is surgical:
`ts
// Invalidate all project queries
queryClient.invalidateQueries({ queryKey: projectKeys.all })
// Invalidate only list queries
queryClient.invalidateQueries({ queryKey: projectKeys.lists() })
`
Pattern 2: Optimistic Updates
`ts
const { mutate: toggleLike } = useMutation({
mutationFn: (postId: string) => api.toggleLike(postId),
onMutate: async (postId) => {
await queryClient.cancelQueries({ queryKey: postKeys.detail(postId) })
const previous = queryClient.getQueryData(postKeys.detail(postId))
queryClient.setQueryData(postKeys.detail(postId), (old: Post) => ({
...old,
liked: !old.liked,
likeCount: old.liked ? old.likeCount - 1 : old.likeCount + 1,
}))
return { previous }
},
onError: (_, postId, context) => {
queryClient.setQueryData(postKeys.detail(postId), context?.previous)
},
onSettled: (_, __, postId) => {
queryClient.invalidateQueries({ queryKey: postKeys.detail(postId) })
},
})
`
Pattern 3: Dependent Queries
`ts
function UserDashboard({ userId }: { userId: string }) {
const { data: user } = useQuery({
queryKey: userKeys.detail(userId),
queryFn: () => fetchUser(userId),
})
const { data: projects } = useQuery({
queryKey: projectKeys.list({ userId }),
queryFn: () => fetchUserProjects(userId),
enabled: !!user, // only runs when user is loaded
})
// ...
}
`
Pattern 4: Prefetching on Hover
`ts
function ProjectCard({ project }: { project: Project }) {
const queryClient = useQueryClient()
return (
href={/projects/${project.id}}
onMouseEnter={() => {
queryClient.prefetchQuery({
queryKey: projectKeys.detail(project.id),
queryFn: () => fetchProject(project.id),
staleTime: 10 * 1000,
})
}}
>
{project.name}
)
}
``
Users navigate to an already-loaded page. This is the easiest performance win in any list→detail flow.