Skip to content

MediaProvider

MediaProvider from @media-sdk/native wraps your React Native application (or a subtree) and supplies a MediaClient via React context. All hooks except standalone utilities must be called inside a MediaProvider tree.

bash
pnpm add @media-sdk/core@^0.3.1 @media-sdk/native@^0.1.0 react

Props

PropTypeRequiredDescription
clientMediaClientYesAny MediaClient implementation (PexelsMediaClient, PixabayMediaClient, or custom)
childrenReactNodeYesChild components that call hooks

Example

tsx
import { MediaProvider } from "@media-sdk/native";
import {
  ApiKeyProvider,
  PexelsMediaClient,
} from "@media-sdk/core";

const client = new PexelsMediaClient(
  new ApiKeyProvider(process.env.EXPO_PUBLIC_PEXELS_API_KEY!),
);

export function AppRoot({ children }: { children: React.ReactNode }) {
  return (
    <MediaProvider client={client}>
      {children}
    </MediaProvider>
  );
}

When you swap the client prop (for example, switching from Pexels to Pixabay at runtime), hooks re-subscribe and useMediaCapabilities() returns the new provider's capabilities.

Multi-provider setup

Construct clients at the app shell and pass the active client to MediaProvider:

tsx
import { useMemo, useState } from "react";
import { MediaProvider } from "@media-sdk/native";
import {
  ApiKeyProvider,
  PexelsMediaClient,
  PixabayMediaClient,
  type MediaClient,
} from "@media-sdk/core";

type ProviderId = "pexels" | "pixabay";

function createClient(provider: ProviderId): MediaClient {
  if (provider === "pexels") {
    return new PexelsMediaClient(
      new ApiKeyProvider(process.env.EXPO_PUBLIC_PEXELS_API_KEY!),
    );
  }
  return new PixabayMediaClient(
    new ApiKeyProvider(process.env.EXPO_PUBLIC_PIXABAY_API_KEY!),
  );
}

export function AppShell({ children }: { children: React.ReactNode }) {
  const [provider, setProvider] = useState<ProviderId>("pexels");
  const client = useMemo(() => createClient(provider), [provider]);

  return (
    <MediaProvider client={client} key={provider}>
      {children}
    </MediaProvider>
  );
}

Provider selection in settings is fine. Feature tabs and filters must use useMediaCapabilities, not provider === "pexels".


useMediaClient

Returns the MediaClient instance from the nearest MediaProvider.

Returns

The hook returns the client directly (not wrapped in an object):

TypeDescription
MediaClientShared client for direct API calls (searchPhotos, trackView, getCuratedPhotos, etc.)

Example

tsx
import { useMediaClient } from "@media-sdk/native";
import { Pressable, Text } from "react-native";

function TrackViewButton({ photoId }: { photoId: string }) {
  const client = useMediaClient();

  return (
    <Pressable onPress={() => void client.trackView({ mediaId: photoId, mediaType: "photo" })}>
      <Text>Track view</Text>
    </Pressable>
  );
}

Errors

Throws if called outside MediaProvider:

useMediaClient must be used inside a MediaProvider

Next steps