score:25

Accepted answer

when usequery is called by the component, it triggers the query subsequently.

but when uselazyquery is called, it does not trigger the query subsequently, and instead return a function that can be used to trigger the query manually. it is explained on this page: https://www.apollographql.com/docs/react/data/queries/#manual-execution-with-uselazyquery

when react mounts and renders a component that calls the usequery hook, apollo client automatically executes the specified query. but what if you want to execute a query in response to a different event, such as a user clicking a button? the uselazyquery hook is perfect for executing queries in response to events other than component rendering. this hook acts just like usequery, with one key exception: when uselazyquery is called, it does not immediately execute its associated query. instead, it returns a function in its result tuple that you can call whenever you're ready to execute the query.

score:1

something that seems not to be spoken about that i just realize is that uselazyquery doesn't read from the cache. this is somewhat similar to calling the refetch function returned from usequery.

score:4

update:

https://github.com/apollographql/apollo-client/blob/main/changelog.md#improvements-due-to-brainkim-in-8875

uselazyquery now returns a promise as of apollo client 3.5.0 (2021-11-08)

score:16

suppose you have a component where you call usequery, then as soon as the component mounts, usequery runs and the data is fetched from the server. but if you use uselazyquery in that component instead of usequery, query doesn't run and data isn't fetched when component mounts. instead you can run the query based on your requirement, say after clicking a button. example:

import react, { usestate } from 'react';
import { uselazyquery } from '@apollo/client';

function delayedquery() {
  const [dog, setdog] = usestate(null);
  const [getdog, { loading, data }] = uselazyquery(get_dog_photo);

  if (loading) return <p>loading ...</p>;

  if (data && data.dog) {
    setdog(data.dog);
  }

  return (
    <div>
      {dog && <img src={dog.displayimage} />}
      <button onclick={() => getdog({ variables: { breed: 'bulldog' } })}>
        click me!
      </button>
    </div>
  );
}

here, as soon as you click the button, then only the query runs and data is fetched and the image is displayed. but if you had used usequery instead, before clicking the button (i.e when the component mounts), the data would have been fetched and the image would have been displayed


Related Query

More Query from same tag