Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom query hooks inside useQueries in react-query

I created custom hooks for get requests from the server. Below is an example

const usePost = (id: string) => {
    return useQuery(['posts', id], () => getPost(id))
}
const usePosts = () => {
    return useQuery(['posts'], () => getPosts())
}

However, I sometimes need to call multiple queries in a single file, so I would like to use the useQueries hook along with the custom hooks. But when I try to use the custom hooks as the queryFn, React throws me an error saying I can't call a hook inside the function 'queryFn'.

const queries = useQueries([
    {
        queryKey: 'posts',
        queryFn: () => usePosts
    },
    {
        queryKey: ['post', id],
        queryFn: () => usePost(id)
    }
])
// Failed to compile, 'usePost' is called in function 'queryFn' that is neither a React component nor custom hook

How would we be able to use useQueries with custom query hooks?

like image 774
Echo Avatar asked Oct 18 '25 11:10

Echo


1 Answers

This is simply a restriction by the Rule of Hooks in React, that hooks can only be called inside React function components and other React custom hooks.

There are two options to overcome this issue in my opinion:

  1. combine usePost and usePosts in another custom hook
// useAllPosts.js
const useAllPosts = (id: string) => {
  const { data: post } = usePost(id);
  const { data: posts } = usePosts();

  return {
      post,
      posts
  }
}
  1. put the fetcher functions outside of the custom hooks so you can re-use them in other components:
// usePost.js
export const fetchPost = (id: string) => getPost(id);
const usePost = (id: string) => {
  return useQuery(['posts', id], fetchPost)
}

// usePosts.js
export const fetchPosts = () => getPosts();
const usePosts = () => {
  return useQuery(['posts'], () => getPosts())
}

// SomeComponent.jsx
import { fetchPost } from 'usePost';
import { fetchPosts } from 'usePosts';
function SomeComponent() {
  const queries = useQueries([
    {
      queryKey: 'posts',
      queryFn: fetchPosts
    },
    {
      queryKey: ['post', id],
      queryFn: fetchPost
    }
  ]);
}
like image 121
zrkl Avatar answered Oct 22 '25 06:10

zrkl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!