Learn Relay/
← 0810 →

09 - usePreloadedQuery

Learn how to use loadQuery (preloadQuery) + usePreloadedQuery to fetch data at the same time as code.

Exercise

  • add loadQuery inside the loader of path / in routes.tsx and return it as { appQuery }
  • modify App.tsx to use usePreloadedQuery instead of useLazyLoadQuery, reading the preloaded query with useLoaderData()
  • add loadQuery inside the loader of path /post/:id, using params.id as the query variable, and return it as { postDetailQuery }

Click on a post content to open its detail page (PostDetail.tsx).

Extras

  • dispose the preloaded queries when they are not needed anymore
  • preload the post detail query when the user hovers a post

Code Helpers

  • import a compiled query artifact
import AppQuery from './__generated__/AppQuery.graphql';

loadQuery(Environment, AppQuery, {}, { fetchPolicy: 'network-only' });
Next: test usePreloadedQuery →
Loading editor…
localhost:7500 · in-browser GraphQL server
Checks verify your solution against the running app.
  • ○routes.tsx preloads AppQuery with loadQuery
  • ○App uses usePreloadedQuery instead of useLazyLoadQuery
  • ○AppQuery is fetched and the feed is rendered
  • ○Opening a post preloads PostDetailQuery with the post id