How do I use react router with relay?
Asked Answered
W

1

6

I am struggling with react-router and relay integration.

As of now, I stick to this example

It uses the useLazyLoadQuery hook, and although everything seems to work just fine, I also see another way of doing this: usePreloadedQuery.

The docs say that the useLazyLoadQuery hook

can trigger multiple nested or waterfalling round trips if used without caution and waits until render to start a data fetch (when it can usually start a lot sooner than render), thereby degrading performance. Instead, prefer usePreloadedQuery.

However, it is not clear how to integrate this with react-router and obviously, I do not want to reinvent my own router...

Another thing I noticed is that usePreloadedQuery should be used in conjunction with useQueryLoader; At the same time in docs they load it directly by just calling loadQuery();

So I am not sure which way is preferred.

I ended up with a wrapper like this:

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

  // does calling it like this make any sense at all?
  useMemo(() => {
    loadQuery();
  }, [loadQuery]);

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

const HomePage = ({ queryRef }) => {
  const query = usePreloadedQuery(
    graphql`
      query HomePageQuery {
        ...HomePageContainer_repository
      }
    `,
    queryRef
  );

  return (
    <div>
      <HomePageContainer fragmentRef={query} />
    </div>
  );
};
Westmoreland answered 13/7, 2021 at 8:12 Comment(0)
P
0

According to the Relay docs:

The component-based approach of React Router v4 does not readily allow for aggregating the data requirements for nested routes, and as such does not readily permit an approach that will avoid request waterfalls from nesting QueryRenderer components.

So basically using react-router with Relay is out :(

Relay recommends using Found as an alternative router, which is similar to react-router. Found integrates well with Relay using the found-relay package.

Prichard answered 9/2, 2022 at 4:51 Comment(1)
Found does not appear to be well maintained. There is github.com/loop-payments/react-router-relay which uses Relay's EntryPoiny pattern. I'm not a huge fan as it deviates pretty far from normal RouteObjects but maybe it is the best way.Veterinarian

© 2022 - 2024 — McMap. All rights reserved.