Custom Hooks & Patterns in React

From the TanStack Query cheat sheet · Advanced Patterns · verified Jul 2026

Custom Hooks & Patterns

Building reusable query hooks and patterns

typescript
// Custom hook for user data
function useUser(userId: string) {
  return useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetchUser(userId),
    enabled: !!userId,
    staleTime: 1000 * 60 * 5,
  })
}

// Custom hook with mutations
function useUpdateUser() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: updateUser,
    onSuccess: (data) => {
      queryClient.setQueryData(['user', data.id], data)
      queryClient.invalidateQueries({ queryKey: ['users'] })
    }
  })
}

// Usage
function Profile({ userId }) {
  const { data: user, isLoading } = useUser(userId)
  const updateUser = useUpdateUser()

  if (isLoading) return 'Loading...'

  return (
    <div>
      <h1>{user.name}</h1>
      <button onClick={() => updateUser.mutate({ id: userId, name: 'New Name' })}>
        Update
      </button>
    </div>
  )
}
💡 Create custom hooks to encapsulate query logic
⚡ Generic CRUD hooks reduce boilerplate significantly
📌 Debounced queries prevent excessive API calls
🟢 Keep hooks focused on single responsibility
hookspatternsreusable

Continue with TanStack Query

Save the full cheat sheet or work through every related task.

More React tasks

Back to the full TanStack Query cheat sheet