Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useQuery called multiple times when dropdown is opened

I am using "react-query" to call an API from a component . For the purpose of this question , I am returning a mock response from the API .

Every time , I open the dropdown , the useQuery function is called which in turn calls the mock API .

App.js

import React from 'react';
import './style.css';
import { QueryClient, QueryClientProvider } from 'react-query';
import { DropDown } from './Dropdown.js';
const queryClient = new QueryClient();
export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <DropDown />
      </div>
    </QueryClientProvider>
  );
}

Dropdown.js

import React from 'react';
import { useQuery } from 'react-query';

export const DropDown = () => {
  console.log('DropDown re-rendered');

  const { data, isLoading, isError } = useQuery('API', () => {
    return new Promise((resolve, reject) => {
      console.log('API called');
      resolve(['mockData']);
    });
  });

  return (
    <>
      <select>
        <option> 1 </option>
        <option> 2 </option>
      </select>
    </>
  );
};

You can find the demo here : https://react-quxtxd.stackblitz.io

In the console you will see that every time you open the dropdown , useQuery is called.

Stackblitz Editor url : https://stackblitz.com/edit/react-quxtxd?file=src/Dropdown.js

As an alternative to avoid this , I can use the traditional useEffect to make the API calls but I was looking at leveraging the caching advantage that useQuery provides but I am stuck due to this "re-rendering" issue .

Any suggestions / modifications ?

like image 544
Ananth Kumble Avatar asked Dec 11 '25 21:12

Ananth Kumble


2 Answers

This works for me

{ refetchOnWindowFocus: false }

Usage:

const { data, status } = useQuery("users", fetchUsers, { 
    refetchOnWindowFocus: false 
});

If all your queries need this config. It's good to add this to defaultOptions of your queryClient

// App.tsx

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
    },
  },
});

<QueryClientProvider client={queryClient}>
...
</QueryClientProvider>
like image 170
Anjan Talatam Avatar answered Dec 13 '25 09:12

Anjan Talatam


It seems that the original stackblitz has been fixed, so the issue is no longer reproducible. For posterity:

You've probably seen a background refetch due to focusing the window. This is because staleTime defaults to 0 and refetchOnWindowFocus defaults to true. You can either turn off the flag, or set a higher staleTime (recommended).

like image 24
TkDodo Avatar answered Dec 13 '25 10:12

TkDodo



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!