How to trigger useQuery with a button click - React Query

How to trigger useQuery with a button click - React Query

A recent site visitor asked me how to trigger useQuery when they click on a button and I pulled up an example that I use.

By default, useQuery fetches immediately when the component calling it mounts, but not everyone wants this behaviour.

Method 1: Enabled Boolean

You're able to set the default behaviour to NOT fetch data immediately using a key enabled and setting it to false

  const { data } = useQuery("comments", fetchComments, {
    enabled: false
  });

If we want to use a button to trigger this we can maintain a piece of state that holds true or false and then pass the setEnabled method to a button.

On click, the query will fetch the data.

  const [enabled, setEnabled] = useState(false);

  const { data } = useQuery("comments", fetchComments, {
    enabled: enabled
  });

<button onClick={() => setEnabled(true)}>Some Button</button>

Method 2: Refetch()

My preferred method is to use refetch . This is a method that comes with useQuery and is closer to the functionality many of us are looking for in this scenario.

The data is not fetched automatically. We have turned it off using enabled: false .

We can then pass the refetch method to our button to grab the data on demand without toggling any state.

export const useComments = () => {
  const { data, refetch } = useQuery("comments", fetchComments, {
    enabled: false
  });

<button onClick={() => refetch()}>Some Button</button>