website/versioned_docs/version-v20.0.0/api-reference/hooks/use-preloaded-query.md
import DocsRating from '@site/src/core/DocsRating';
usePreloadedQueryHook used to access data fetched by an earlier call to loadQuery or with the help of useQueryLoader. This implements the "render-as-you-fetch" pattern:
loadQuery callback returned from useQueryLoader. This will store a query reference in React state.
loadQuery directly, which returns a query reference. In that case, store the item in state or in a React ref, and call dispose() on the value when you are no longer using it.usePreloadedQuery(). This call will suspend if the query is still pending, throw an error if it failed, and otherwise return the query results.useLazyLoadQuery() as it can allow fetching data earlier while not blocking rendering.For more information, see the Rendering Queries guide.
import type {AppQueryType} from 'AppQueryType.graphql';
const React = require('React');
const {graphql, useQueryLoader, usePreloadedQuery} = require('react-relay');
const AppQuery = graphql`
query AppQuery($id: ID!) {
user(id: $id) {
name
}
}
`;
type Props = {
initialQueryRef: PreloadedQuery<AppQueryType>,
};
function NameLoader(props) {
const [queryReference, loadQuery] = useQueryLoader(
AppQuery,
props.initialQueryRef, /* e.g. provided by router */
);
return (<>
<Button
onClick={() => loadQuery({id: '4'})}
disabled={queryReference != null}
>
Reveal your name!
</Button>
<Suspense fallback="Loading...">
{queryReference != null
? <NameDisplay queryReference={queryReference} />
: null
}
</Suspense>
</>);
}
function NameDisplay({ queryReference }) {
const data = usePreloadedQuery(AppQuery, queryReference);
return <h1>{data.user?.name}</h1>;
}
query: GraphQL query specified using a graphql template literal.preloadedQueryReference: A PreloadedQuery query reference, which can be acquired from useQueryLoader or by calling loadQuery() .data: Object that contains data which has been read out from the Relay store; the object matches the shape of specified query.
data above is: { user: ?{ name: ?string } }.