Skip to main content
This page covers the React hooks from @grainql/analytics-web, which provide remote configuration and advanced React integration. For basic analytics tracking in React, you can use @grainql/tag directly — see the React Quick Start.

Why React Hooks?

Grain’s React hooks eliminate boilerplate and provide a React-friendly API for analytics and remote configuration. Without hooks:
With hooks:
Same functionality, much simpler.

Installation

React 16.8+ is required (peer dependency, not bundled).

Quick Start

Wrap your app with GrainProvider, then use hooks in components:

Available Hooks

useConfig

Get a single configuration value with cache-first loading:
Automatically re-renders when configuration changes. Perfect for feature flags and dynamic content.

useAllConfigs

Get all configurations as an object:
Use when you need multiple config values or want to iterate over all configurations.

useTrack

Get a stable track function that doesn’t cause re-renders:
Why this matters: The function reference never changes, preventing unnecessary re-renders in child components.

useGrainAnalytics

Access the full Grain client for advanced operations:
Use this when you need functionality beyond the specialized hooks.

The Provider

GrainProvider sets up Grain for your app. Two patterns available: Provider-managed (recommended):
External client (advanced):
Provider-managed is simpler for most cases. Use external client when you need to share the instance across multiple providers or need access outside React.

Key Benefits

Cache-First Loading: Hooks return cached values immediately, then fetch fresh data in the background. Your UI never waits for network requests. Automatic Updates: Components automatically re-render when configurations change. No manual listener management. Performance Optimized: Hooks use React’s built-in optimization (memo, useCallback) to prevent unnecessary re-renders. Type Safe: Full TypeScript support with type inference for all hooks and props. React Patterns: Follows React conventions with hooks, context, and functional patterns.

Context API Explanation

If you’re new to React’s Context API, here’s how it works with Grain: Context lets you share values across your component tree without passing props manually. GrainProvider creates a context with the Grain client:
Any component inside the provider can use Grain hooks, no matter how deeply nested. No prop drilling needed.

Common Patterns

Feature Flag

A/B Test

User Authentication

Grain Tag vs Analytics Web for React

Compared to Vanilla SDK

Both are powerful. Use hooks for React apps, vanilla SDK for other frameworks or environments.

Next Steps

GrainProvider

Learn about provider setup

useConfig Hook

Master configuration access

useTrack Hook

Efficient event tracking

React Example

See a complete example