Skip to the content

useEnvironment / EnvironmentProvider

EnvironmentProvider is the single Relay provider for an app. It publishes the Environment to the tree and mounts react-relay's RelayEnvironmentProvider over it, so one mount serves both the useEnvironment() hook and every react-relay hook.
Relay

When to use

Use when
  • mounting Relay at the app root — useLazyLoadQuery, usePreloadedQuery, useFragment and useSubscription all resolve under it;
  • a component needs the Environment imperatively, for commitMutation or fetchQuery;
  • a test injects a MockEnvironment. relay-test-utils is your app's test dependency, not a runtime dependency of this package.
Avoid when
  • you are about to add RelayEnvironmentProvider yourself — EnvironmentProvider already mounts it;
  • you want a provider per subtree — a nested EnvironmentProvider only shadows the environment there.

Usage

import { useLazyLoadQuery } from 'react-relay';
import { commitMutation } from '@apollion-dsi/relay/commitMutation';
import { useEnvironment } from '@apollion-dsi/relay/useEnvironment';
import ProfileQuery from './__generated__/ProfileQuery.graphql';

function Profile() {
  const { environment } = useEnvironment();
  const data = useLazyLoadQuery(ProfileQuery, {});
  const save = () => commitMutation(environment, { mutation: SaveMutation, variables: {} });
  return <button onClick={save}>Save {data.viewer?.username}</button>;
}

Mount it under one <EnvironmentProvider environment={Environment}>, with Environment from CreateRelayEnvironment. The provider value is memoized on environment, so a stable environment does not rebuild the context value. useEnvironment() throws outside the provider.

An app that still wraps its tree in RelayEnvironmentProvider over the same environment keeps working — the nearest provider wins and it is the same instance. Migrating is a deletion.

See also