DEV Community

Cover image for How to trigger useQuery with a button click - React Query
Calvin Torra
Calvin Torra

Posted on • Edited on • Originally published at calvintorra.com

6

How to trigger useQuery with a button click - React Query

Join my newsletter Here:

Once a week, I share my best finds on:

  • AWS
  • JavaScript
  • Web Scraping
  • Indie Hacking

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
  });
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Join my newsletter Here:

Once a week, I share my best finds on:

  • AWS
  • JavaScript
  • Web Scraping
  • Indie Hacking

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay