Why React Hooks?
Grain’s React hooks eliminate boilerplate and provide a React-friendly API for analytics and remote configuration. Without hooks:Installation
Hooks are included in the main package:Quick Start
Wrap your app withGrainProvider, then use hooks in components:
Available Hooks
useConfig
Get a single configuration value with cache-first loading:useAllConfigs
Get all configurations as an object:useTrack
Get a stable track function that doesn’t cause re-renders:useGrainAnalytics
Access the full Grain client for advanced operations:The Provider
GrainProvider sets up Grain for your app. Two patterns available:
Provider-managed (recommended):
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:
Common Patterns
Feature Flag
A/B Test
User Authentication
Compared to Vanilla SDK
| Feature | Vanilla SDK | React Hooks |
|---|---|---|
| Setup | Manual instance | Provider + hooks |
| State management | Manual useState | Automatic |
| Listeners | Manual add/remove | Automatic |
| Re-renders | Manual updates | Automatic |
| Cleanup | Manual in useEffect | Automatic |
| Boilerplate | More code | Minimal code |