What's the difference between usePreloadedQuery and useQueryLoader?

667 Views Asked by At

I'm learning graphQL and react-relay library.

In these 2 sections:

  1. Rendering Queries: introduce usePreloadedQuery.
  2. Fetching Queries for Render: introduce useQueryLoader.

For short, I will say 1st-query instead of usePreloadedQuery, 2nd-query for useQueryLoader.

Question-1

The 1st-query will use a graphQL and it's generated flow type, query the server, then return the data. That's OK to me.

The 2nd-query seems to do the same thing? What's the difference except the library API/syntax?

Question-2

Here's the sample code in the 2nd section:

import type {HomeTabQuery as HomeTabQueryType} from 'HomeTabQuery.graphql';
import type {PreloadedQuery} from 'react-relay';

const HomeTabQuery = require('HomeTabQuery.graphql')
const {useQueryLoader} = require('react-relay');


type Props = {
  initialQueryRef: PreloadedQuery<HomeTabQueryType>,
};

function AppTabs(props) {
  const [
    homeTabQueryRef,
    loadHomeTabQuery,
  ] = useQueryLoader<HomeTabQueryType>(
    HomeTabQuery,
    props.initialQueryRef, /* e.g. provided by router */
  );

  const onSelectHomeTab = () => {
    // Start loading query for HomeTab immediately in the event handler
    // that triggers navigation to that tab, *before* we even start
    // rendering the target tab.
    // Calling this function will update the value of homeTabQueryRef.
    loadHomeTabQuery({id: '4'});

    // ...
  }

  // ...

  return (
    screen === 'HomeTab' && homeTabQueryRef != null ?
      // Pass to component that uses usePreloadedQuery
      <HomeTab queryRef={homeTabQueryRef} /> :
      // ...
  );
}

The line-1 use import type {HomeTabQuery as HomeTabQueryType} from 'HomeTabQuery.graphql'. And the line-4 use const HomeTabQuery = require('HomeTabQuery.graphql').

I don't understand, aren't these 2 lines do the same thing?

1

There are 1 best solutions below

0
On

I guess one of the obvious differences is you can use useQueryLoader for loading your query on demand. On the other hand, you can you use usePreloadedQuery for situations like render as you fetch.