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.
useConfig and useTrack.
Provider-Managed Pattern
The simplest way - let the provider create and manage the Grain client:External Client Pattern
Create the client yourself, then pass it to the provider:- 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:userId changes, the provider updates the Grain client automatically. No manual setUserId() calls needed.
Multiple Providers
You can nest providers for different tenants (rare):Provider Position
Place the provider high in your component tree:Error Handling
If hooks are used outside a provider, you’ll get an error:Configuration Updates
Configuration changes cause provider to re-render children. Use stable config objects:useMemo if config is complex or changes frequently.
With Next.js
In Next.js, wrap your app in_app.tsx: