Fixing multiple renders with NextJs and tRPC

Tagged: nextjstrpc
Photo by Mo Eid
Photo by Mo Eid

While I was developing my own starter kit for my apps (using tRPC with NextJs), I noticed that when I tried to use trpc.useQuery() in a component, I was getting a frustrating number of multiple renders (two to four at a time) on even the simplest of pages.

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

After some research and experimentation, I figured out what was happening. My React Query was fetching the data on the component’s mounting.

That also had the side effect of changing the data on the screen on every reload and pinging the backend API twice, which is completely unnecessary.

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