You need to create another hook similar to `useQuery` named `useLazyQuery`. In `useQuery`, the code is executed inside a `useEffect. In the new `useLazyQuery` that you’d create, you’d simply return a function that , when triggered, would call the code that currently runs inside the effect.

Thus, you’d remove the effect, put the code in a function and return it as the response of `useLazyQuery`. Then you can call it on click.

For example:


const queryData = useLazyQuery({

url : … ,

params: …


<button onClick={queryData}>clickme</button>


Normally you’d be using a library to handle that for you (not write a custom hook like I did in the article. This was for done purely for showcasing purposes). A library like react-query would help out here since it has all that implemented out of the box



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store