React SDK
React client side library for Reflag.com
Reflag supports flag toggling, tracking flag usage, requesting feedback on features, and remotely configuring flags.
The Reflag React SDK comes with a built-in toolbar which appears on localhost by default.
Install
Install via npm:
npm i @reflag/react-sdkGet started
1. Add the ReflagProvider context provider
ReflagProvider context providerAdd the ReflagProvider context provider to your application:
Example:
import { ReflagProvider } from "@reflag/react-sdk";
<ReflagProvider
publishableKey="{YOUR_PUBLISHABLE_KEY}"
context={{
company: { id: "acme_inc", plan: "pro" },
user: { id: "john doe" },
}}
loadingComponent={<Loading />}
>
{/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */}
</ReflagProvider>;2. Create a new flag and set up type safety
Install the Reflag CLI:
Run npx reflag new to create your first flag! On the first run, it will sign into Reflag and set up type generation for your project:
[!Note] By default, types will be generated in
gen/flags.d.ts. The defaulttsconfig.jsonfileincludes this file by default, but if yourtsconfig.jsonis different, make sure the file is covered in theincludeproperty.
3. Use useFlag(<flagKey>) to get flag status
useFlag(<flagKey>) to get flag statusUsing the useFlag hook from your components lets you toggle flags on/off and track flag usage:
Example:
useFlag can help you do much more. See a full example for useFlag see below.
Setting context
Reflag determines which flags are active for a given user, company, or other context. You can pass these to the ReflagProvider using the context prop.
Using the context prop
context propLegacy individual props (deprecated)
For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version:
[!Important] The
user,company, andotherContextprops are deprecated. Use thecontextprop instead, which provides the same functionality in a more structured way.
Context requirements
If you supply user or company objects, they must include at least the id property otherwise they will be ignored in their entirety. In addition to the id, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. Attributes which are not properties of the user or company can be supplied using the other property.
Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. A number of special attributes exist:
name-- display name foruser/company,email-- the email of the user,avatar-- the URL foruser/companyavatar image.
To retrieve flags along with their targeting information, use useFlag(key: string) hook (described in a section below).
Note that accessing isEnabled on the object returned by useFlag() automatically generates a check event.
Remote config
Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it.
Similar to isEnabled, each flag accessed using the useFlag() hook, has a config property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary isEnabled you can have multiple configuration values which are given to different user/companies.
Get started with Remote config
Update your flag definitions:
key is mandatory for a config, but if a flag has no config or no config value was matched against the context, the key will be undefined. Make sure to check against this case when trying to use the configuration in your application. payload is an optional JSON value for arbitrary configuration needs.
Note that, similar to isEnabled, accessing config on the object returned by useFlag() automatically generates a check event.
Toolbar
The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off.
The toolbar will automatically appear on localhost. However, it can also be incredibly useful in production. You have full control over when it appears through the toolbar configuration option passed to the ReflagProvider.
You can pass a simple boolean to force the toolbar to appear/disappear:
Server-side rendering and bootstrapping
For server-side rendered applications, you can eliminate the initial network request by bootstrapping the client with pre-fetched flag data using the ReflagBootstrappedProvider.
Using ReflagBootstrappedProvider
ReflagBootstrappedProviderThe <ReflagBootstrappedProvider> component is a specialized version of ReflagProvider designed for server-side rendering and preloaded flag scenarios. Instead of fetching flags on initialization, it uses pre-fetched flags, resulting in faster initial page loads and better SSR compatibility.
Server-side endpoint setup
Create an endpoint that provides bootstrap data to your client application:
Next.js Page Router SSR example
For Next.js applications using server-side rendering, you can pre-fetch flags in getServerSideProps:
This approach eliminates loading states and improves performance by avoiding the initial flags API call.
Next.js App Router example
For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components:
This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed.
<ReflagClientProvider> component
<ReflagClientProvider> componentThe <ReflagClientProvider> is a lower-level component that accepts a pre-initialized ReflagClient instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application.
Usage
Props
The ReflagClientProvider accepts the following props:
client: A pre-initializedReflagClientinstanceloadingComponent: Optional React component to show while the client is initializing (same asReflagProvider)
[!Note] Most applications should use
ReflagProviderorReflagBootstrappedProviderinstead ofReflagClientProvider. Only use this component when you need the advanced control it provides.
<ReflagProvider> component
<ReflagProvider> componentThe <ReflagProvider> initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props:
publishableKeyis used to connect the provider to an environment on Reflag. Find yourpublishableKeyunder environment settings in Reflag,context(recommended): An object containinguser,company, andotherproperties that make up the evaluation context used to determine if a flag is enabled or not.companyandusercontexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc.company,userandother(deprecated): Individual props for context. These are deprecated in favor of thecontextprop and will be removed in the next major version.[!Note] If you specify
companyand/oruserthey must have at least theidproperty, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against,fallbackFlags: A list of strings which specify which flags to consider enabled if the SDK is unable to fetch flags. Can be provided in two formats:timeoutMs: Timeout in milliseconds when fetching flags from the server.staleWhileRevalidate: If set totrue, stale flags will be returned while refetching flags in the background.expireTimeMs: If set, flags will be cached between page loads for this duration (in milliseconds).staleTimeMs: Maximum time (in milliseconds) that stale flags will be returned ifstaleWhileRevalidateis true and new flags cannot be fetched.offline: Provide this option when testing or in local development environments to avoid contacting Reflag servers.loadingComponentlets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens,useFlag()anduseIsLoadingreturnsisLoadingwhich you can use to customize the loading experience.enableTracking: Set tofalseto stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults totrue),apiBaseUrl: Optional base URL for the Reflag API. Use this to override the default API endpoint,appBaseUrl: Optional base URL for the Reflag application. Use this to override the default app URL,sseBaseUrl: Optional base URL for Server-Sent Events. Use this to override the default SSE endpoint,debug: Set totrueto enable debug logging to the console,toolbar: Optional configuration for the Reflag toolbar,feedback: Optional configuration for feedback collection
<ReflagBootstrappedProvider> component
<ReflagBootstrappedProvider> componentThe <ReflagBootstrappedProvider> is a specialized version of the ReflagProvider that uses pre-fetched flag data instead of making network requests during initialization. This is ideal for server-side rendering scenarios.
The component accepts the following props:
flags: Pre-fetched flags data of typeBootstrappedFlagsobtained from the Node SDK'sgetFlagsForBootstrap()method. This contains both the context (user, company, other) and the flags data.All other props available in
ReflagProviderare supported exceptcontext,user,company, andother(which are extracted fromflags.context).
Example:
[!Note] When using
ReflagBootstrappedProvider, the context (user, company, and other) is extracted from theflags.contextproperty and doesn't need to be passed separately.
Hooks
useFlag()
useFlag()Returns the state of a given flag for the current context. The hook provides type-safe access to flags and their configurations.
useTrack()
useTrack()useTrack() lets you send custom events to Reflag. Use this whenever a user uses a feature. These events can be used to analyze feature usage in Reflag.
useRequestFeedback()
useRequestFeedback()useRequestFeedback() returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See Automated Feedback Surveys for how to do this automatically, without code.
When using the useRequestFeedback you must pass the flag key to requestFeedback. The example below shows how to use position to ensure the popover appears next to the "Give feedback!" button.
See the Feedback Documentation for more information on requestFeedback options.
useSendFeedback()
useSendFeedback()Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag.
useUpdateUser(), useUpdateCompany() and useUpdateOtherContext()
useUpdateUser(), useUpdateCompany() and useUpdateOtherContext()These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session.
useClient()
useClient()Returns the ReflagClient used by the ReflagProvider. The client offers more functionality that is not directly accessible thorough the other hooks.
useIsLoading()
useIsLoading()Returns the loading state of the flags in the ReflagClient. Initially, the value will be true if no bootstrap flags have been provided and the client has not be initialized.
useOnEvent()
useOnEvent()Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount.
Migrating from Bucket SDK
If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK:
Bucket*classes, and types have been renamed toReflag*(e.g.BucketClientis nowReflagClient)Feature*classes, and types have been renamed toFlag*(e.g.Featureis nowFlag,RawFeaturesis nowRawFlags)When using strongly-typed flags, the new
Flagsinterface replacedFeaturesinterfaceAll methods that contained
featurein the name have been renamed to use theflagterminology (e.g.getFeatureisgetFlag)The
fallbackFeaturesproperty in client constructor and configuration files has been renamed tofallbackFlagsfeatureKeyhas been renamed toflagKeyin all methods that accepts that argumentThe SDKs will not emit
evaluateandevaluate-configevents anymoreThe new cookies that are stored in the client's browser are now
reflag-*prefixed instead ofbucket-*The
featuresUpdatedhook has been renamed toflagsUpdatedThe
checkIsEnabledandcheckConfighooks have been removed, usecheckfrom now on
To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods:
getFeaturemethod is an alias forgetFlaggetFeaturesmethod is an alias forgetFlagsuseFeaturemethod is an alias foruseFlagfeaturesUpdatedhook is an alias forflagsUpdated
If you are running with strict Content Security Policies active on your website, you will need change them as follows:
connect-src https://front.bucket.cotoconnect-src https://front.reflag.com
Content Security Policy (CSP)
See CSP for info on using Reflag React SDK with CSP
License
MIT License
Copyright (c) 2025 Bucket ApS
Last updated
Was this helpful?