react-relay-example icon indicating copy to clipboard operation
react-relay-example copied to clipboard

useLazyLoadQuery vs usePreloadedQuery

Open tar-aldev opened this issue 4 years ago • 0 comments

First of all, thank you for your example, it helped me to get at least something from relay (as docs are sometimes controversial and not clear).

I found that in the migration guide they say that useLazyLoadQuery can be used. However, in the useLazyLoadQuery description, they say Instead, prefer usePreloadedQuery. https://relay.dev/docs/api-reference/use-lazy-load-query/#uselazyloadquery

The problem with usePreloadedQuery to me is that it gets queryRef out of nowhere in all examples. They say I should handle it in routing, but I don't think react-router allows to do this.

Although it could be done like this

const WrappedHomePage = () => {
  const [queryRef, loadQuery] = useQueryLoader(HomePageQuery);

  useMemo(() => {
    loadQuery();
  }, [loadQuery]);

  return <HomePage queryRef={queryRef} />;
};

const HomePage = ({ queryRef }) => {
  const query = usePreloadedQuery(
    graphql`
      # By convention it should be <ComponentName></ComponentName>
      query HomePageQuery {
        ...HomePageContainer_repository
      }
    `,
    queryRef
  );

  return (
    <div>
      <HomePageContainer fragmentRef={query} />
    </div>
  );
};

I am not sure whether it is better at all. Could anyone suggest a solution of integrating it with react-router and use preloaded query?

tar-aldev avatar Jul 13 '21 08:07 tar-aldev