Skip to main content

What is GrainProvider?

GrainProvider is a React component that makes Grain available throughout your app using React’s Context API. Wrap your app with it once, then use hooks anywhere.
Now any component inside can use Grain hooks like useConfig and useTrack.

Provider-Managed Pattern

The simplest way - let the provider create and manage the Grain client:
Pass any configuration options:
When to use: Most apps. Simple, works great, no external client needed.

External Client Pattern

Create the client yourself, then pass it to the provider:
When to use:
  • Need to access Grain outside React components
  • Want to share one instance across multiple apps
  • Need full control over client lifecycle

Dynamic User ID

Update the user ID when authentication changes:
What happens: When userId changes, the provider updates the Grain client automatically. No manual setUserId() calls needed.

Multiple Providers

You can nest providers for different tenants (rare):
Inner provider overrides outer one for components inside it.

Provider Position

Place the provider high in your component tree:

Error Handling

If hooks are used outside a provider, you’ll get an error:
Always wrap your app with the provider before using hooks.

Configuration Updates

Configuration changes cause provider to re-render children. Use stable config objects:
The second example works but may cause unnecessary re-renders. Use useMemo if config is complex or changes frequently.

With Next.js

In Next.js, wrap your app in _app.tsx:
For App Router:

Next Steps

useConfig

Access remote configurations

useTrack

Track events efficiently