Skip to main content
GrainProvider puts one GrainAnalytics client into React context. Every hook under @grainql/analytics-web/react reads the client from this context. Mount the provider one time, above every component that calls a hook.

Props

Pass config or client, not both. The provider throws an error when it receives both props, and when it receives neither.

Provider-managed client

Pass config. The provider creates the client on its first render and calls destroy() on the client when the provider unmounts.
The provider reads config one time. A later change to the config prop does not reach the client. To change the user after login, call identify or login on the client. Read useGrainAnalytics.

External client

Create the client yourself and pass it as client. The provider does not destroy this client. You own its lifecycle.
Use this pattern when code outside React sends events with the same client, for example a router hook or an API layer.

Position in the tree

Place the provider above the router and above every component that calls a hook. A hook called in a component outside the provider throws an error with the text useGrainAnalytics must be used within a GrainProvider. Nested providers are allowed. A component reads the nearest provider above it.

Next.js

The provider uses React context, so it must be in a Client Component. In the App Router, put the provider in a file with the 'use client' directive and mount that file in the root layout.
In the Pages Router, wrap the page component in pages/_app.tsx.
Read Next.js.