Fixing multiple renders with NextJs and tRPC

Tagged: nextjstrpc
Photo by Mo Eid
Photo by Mo Eid

In my personal starter kit I am using tRPC with NextJs. I noticed that when I tried to use trcp.useQuery() in an a component I was getting a frustrating amount of multiple renders (two to four at a time).

Why do my pages render twice, or render multiple times?

After some research I found out that what is happening is React Query is fetching the data on the mounting of the component.

This also had the side effect of not only changing the data on the screen on every reload, but pinged the backend api twice.

The solution

Look at your _app.tsx in your /pages folder. In the withTrpc section and in the config({ ctx }) { add this to the return block:

queryClientConfig: {
    defaultOptions: {
        queries: {
            refetchOnMount: false,
        },
    },
},

Why is it whenever I click in the window it refetches?

This is because if a default feature in React Query. The Window Focus Refreshing feature is so that when your user comes back to the page (after browsing in another tab or something) and clicks inside of it React Query will fetch fresh data for you in the background.

Learn about the important defaults of React Query.

Now, in most cases you will want this on when other users are adding content to your application and you want your user to have the most up to date data. However, in my case I wanted it off so it’s as simple as turning off the refetchOnWindowFocus option:

queryClientConfig: {
    defaultOptions: {
        queries: {
            refetchOnWindowFocus: false,
        },
    },
},

My final _app.tsx looks like this:

export default withTRPC<AppRouter>({
  config({ ctx }) {
    return {
      url: `${getBaseUrl()}/api/trpc`,
      queryClientConfig: {
        defaultOptions: {
          queries: {
            refetchOnMount: false,
            refetchOnWindowFocus: false,
          },
        },
      },
    };
  },
  ssr: true,
})(MyApp);

Profile picture

Written by who lives and works in Wisconsin building useful things, and thinks that pineapple on pizza is okay. You should follow them on Twitter