How to use @shopify/react-hooks - 10 common examples

To help you get started, we’ve selected a few @shopify/react-hooks examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Shopify / quilt / packages / react-i18n / src / hooks.tsx View on Github external
const i18nRef = React.useRef(i18n);

  React.useEffect(() => {
    return unsubscribeRef.current;
  }, []);

  // We use refs in this component so that it never changes. If this component
  // is regenerated, it will unmount the entire tree of the previous component,
  // which is usually not desirable. Technically, this does leave surface area
  // for a bug to sneak in: if the component that renders this does so inside
  // a component that blocks the update from passing down, nothing will force
  // this component to re-render, so no descendants will get the new ids/ i18n
  // value. Because we don't actually have any such cases, we're OK with this
  // for now.
  const shareTranslationsComponent = useLazyRef(
    () =>
      function ShareTranslations({children}: {children: React.ReactNode}) {
        return (
          
            
              {children}
            
          
        );
      },
  );

  return [i18n, shareTranslationsComponent.current];
}
github Shopify / quilt / packages / react-i18n / src / hooks.tsx View on Github external
function useComplexI18n(
  {id, fallback, translations}: Partial,
  manager: I18nManager,
): Result {
  const managerRef = React.useRef(null);
  const unsubscribeRef = React.useRef>(
    noop,
  );
  const parentIds = React.useContext(I18nIdsContext);

  // Parent IDs can only change when a parent gets added/ removed,
  // which would cause the component using `useI18n` to unmount.
  // We also don't support the `id` changing between renders. For these
  // reasons, it's safe to just store the IDs once and never let them change.
  const ids = useLazyRef(() => (id ? [id, ...parentIds] : parentIds));

  // When the manager changes, we need to do the following IMMEDIATELY (i.e.,
  // not in a useEffect callback):
  //
  // 1. Register the component’s translations. This ensures that the first render gets
  //    the synchronous translations, if available.
  // 2. Unsubscribe from changes to a previous manager.
  // 3. Subscribe to changes from the new manager. This ensures that if the subscription
  //    is updated between render and `useEffect`, the state update is not lost.
  if (manager !== managerRef.current) {
    managerRef.current = manager;

    unsubscribeRef.current();
    unsubscribeRef.current = manager.subscribe(
      ids.current,
      ({translations, loading}, details) => {
github Shopify / quilt / packages / react-import-remote / src / hooks.ts View on Github external
export function useImportRemote(
  source: string,
  options: Options,
): {
  result: Result;
  intersectionRef: React.Ref;
} {
  const {defer = DeferTiming.Mount, nonce = '', getImport} = options;
  const [result, setResult] = React.useState>({
    status: Status.Initial,
  });
  const idleCallbackHandle = React.useRef(
    null,
  );
  const mounted = useMountedRef();

  const deferOption = React.useRef(defer);

  if (deferOption.current !== defer) {
    throw new Error(
      [
        'You’ve changed the defer strategy on an ',
        'component after it has mounted. This is not supported.',
      ].join(' '),
    );
  }

  let intersection: IntersectionObserverEntry | null = null;
  let intersectionRef: React.Ref = null;

  // Normally this would be dangerous but because we are
github Shopify / quilt / packages / react-async / src / hooks.ts View on Github external
export function useAsync(
  resolver: Resolver,
  {assets, scripts = assets, styles = assets, immediate = true}: Options = {},
) {
  const [value, setValue] = useState(() =>
    immediate || typeof window !== 'undefined' ? resolver.resolved : null,
  );

  const mounted = useMountedRef();

  const load = useCallback(async (): Promise => {
    if (value != null) {
      return value;
    }

    try {
      const resolved = await resolver.resolve();

      if (mounted.current) {
        // It's important to use the function form of setValue here.
        // Resolved is going to be a function in most cases, since it's
        // a React component. If you do not set it using the function form,
        // React treats the component as the function that returns state,
        // so it sets state with the result of manually calling the component
        // (so, usually JSX).
github Shopify / quilt / packages / react-graphql-universal-provider / src / GraphQLUniversalProvider.tsx View on Github external
export function GraphQLUniversalProvider({
  children,
  createClientOptions,
}: Props) {
  const [initialData, Serialize] = useSerialized('apollo');

  const [client, link] = useLazyRef<
    [
      import('apollo-client').ApolloClient,
      ReturnType
    ]
  >(() => {
    const clientOptions = createClientOptions();
    const link = createSsrExtractableLink();

    const apolloClient = new ApolloClient({
      ...clientOptions,
      link: clientOptions.link ? link.concat(clientOptions.link) : link,
      cache: initialData
        ? clientOptions.cache.restore(initialData)
        : clientOptions.cache,
    });
github Shopify / quilt / packages / react-i18n-universal-provider / src / I18nUniversalProvider.tsx View on Github external
export function I18nUniversalProvider({
  children,
  ...explicitI18nDetails
}: Props) {
  const [serialized, Serialize] = useSerialized('i18n');

  const i18nDetails: I18nDetails = {
    locale: explicitI18nDetails.fallbackLocale || 'en',
    ...(serialized ? serialized : {}),
    ...explicitI18nDetails,
  };

  const manager = useLazyRef(
    () =>
      new I18nManager(
        i18nDetails,
        serialized ? serialized.translations : undefined,
      ),
  ).current;

  useHtmlAttributes({lang: i18nDetails.locale});

  const {onError, ...primitiveI18nDetails} = i18nDetails;

  return (
    <>
      {children}
       {
github Shopify / quilt / packages / react-web-worker / src / hooks.ts View on Github external
export function useWorker(
  creator: WorkerCreator,
  ...args: NoInfer
) {
  const {current: worker} = useLazyRef(() => creator(...(args as any)));

  useEffect(() => {
    return () => {
      terminate(worker);
    };
  }, [worker]);

  return worker;
}
github Shopify / quilt / packages / react-self-serializers / src / GraphQLComponent.tsx View on Github external
export function GraphQL({children, createClient}: Props) {
  const [initialData, Serialize] = useSerialized('apollo');

  const [client, link] = useLazyRef<
    [
      import('apollo-client').ApolloClient,
      ReturnType
    ]
  >(() => {
    const link = createSsrExtractableLink();
    const client = createClient();
    client.link = link.concat(client.link);

    if (initialData) {
      client.cache = client.cache.restore(initialData);
    }

    return [client, link];
  }).current;
github Shopify / quilt / packages / react-hydrate / src / Hydrator.tsx View on Github external
export const Hydrator = React.memo(function Hydrator({children, id}: Props) {
  const manager = React.useContext(HydrationContext);
  const hydrationId = useLazyRef(() => manager.hydrationId(id)).current;
  const hydrationProps = {[HYDRATION_ATTRIBUTE]: hydrationId};

  useServerEffect(() => {}, manager.effect);

  return children ? (
    <div>{children}</div>
  ) : (
    <div>
  );
});
</div>
github Shopify / quilt / packages / react-cookie / src / CookieUniversalProvider.tsx View on Github external
export function CookieUniversalProvider({server, children}: Props) {
  const manager = useNetworkManager();

  const cookieManager = useLazyRef(() =&gt; {
    if (!server &amp;&amp; hasDocumentCookie()) {
      return new BrowserCookieManager();
    }

    if (manager == null) {
      throw new Error(NO_MANAGER_ERROR);
    }

    return manager.cookies;
  }).current;

  return (
    
      {children}
    
  );

@shopify/react-hooks

A collection of primitive React hooks

MIT
Latest version published 5 days ago

Package Health Score

95 / 100
Full package analysis

Similar packages