DEV Community

Ben Read
Ben Read

Posted on

Using react-query with NextJS router

Tanner Lindsey's React Query is a fantastic tool which I've really enjoyed using recently. But we found a few times where we have been using it in close conjunction with multiple requests where it seemed to be returning the same dataset for different queries. Here's what was going on.

Here are the two queries I wrote:

    const data = useReactQuery(
        id,
        getData(id)
    );

    const moreData = useReactQuery(
        id,
        getMoreData(id)
    );
Enter fullscreen mode Exit fullscreen mode

In this case, we were fetching data from 2 different endpoints, but when we inspected the data, it seemed to us as if we had made only one API call.

The problem was that we are using the same key for each of the queries:

    const data = useReactQuery(
        'data',
        getData(id)
    );

    const moreData = useReactQuery(
        'moreData',
        getMoreData(id)
    );
Enter fullscreen mode Exit fullscreen mode

Using unique keys for each request is in fact well documented on the docs site.

Query keys and NextJS routing

I encountered a similar problem when using keys similar to the above on two different pages in a NextJS application. After the original query had been run we did a router.push() to a new page, and had another useQuery() on the next page which used the same key as the previous page.

Again the same thing happened, it seemed to us as if we had made a mistake and mixed the fetch requests around. this happened because changing a route in a hydrated NextJS application only changes the application state, not the browser URL, which would have cleared the react-query state. Ensuring that the keys were unique fixed the issue here as well.

Top comments (0)