npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@flipt-io/flipt-client-react

v0.2.0

Published

Flipt Client Evaluation React SDK

Downloads

24,833

Readme

Flipt React SDK

npm

The Flipt React SDK provides a convenient way to integrate Flipt feature flags into your React applications using a custom hook and a context provider. It is built on top of the Flipt client-side evaluation client for the browser.

Installation

npm install @flipt-io/flipt-client-react

Usage

There are three ways to use the Flipt React SDK.

  1. Use the useFliptBoolean hook for boolean evaluation in a functional component that is wrapped in a FliptProvider.
  2. Use the useFliptVariant hook for variant evaluation in a functional component that is wrapped in a FliptProvider.
  3. Use the useFliptSelector hook for custom evaluation in a functional component that is wrapped in a FliptProvider.

[!TIP] Looking for NextJS support? Check out our NextJS examples in the main Flipt repo.

FliptProvider

First, wrap your application or a part of it with the FliptProvider:

import { FliptProvider } from '@flipt-io/flipt-client-react';

function App() {
  return (
    <FliptProvider
      namespace="default"
      options={{
        url: 'https://your-flipt-instance.com'
        // Add other configuration options as needed
      }}
    >
      {/* Your app components */}
    </FliptProvider>
  );
}

useFliptBoolean Hook

The useFliptBoolean hook simplifies the process of evaluating a boolean feature flag. This hook must be used within a functional component that is wrapped by the FliptProvider context. A default value is returned if the feature flag cannot be evaluated at the current time (e.g., due to network issues or missing data).

import { useFliptBoolean } from '@flipt-io/flipt-client-react';

function MyComponent() {
  const result = useFliptBoolean('my-flag', false, 'user-123', {
    // additional context
  });
  const handleCheckFlag = async () => {
    console.log('Flag evaluation result:', result);
  };

  return (
    <div>
      <button onClick={handleCheckFlag}>Check Flag</button>
    </div>
  );
}

useFliptVariant Hook

The useFliptVariant hook simplifies the process of evaluating a variant feature flag. This hook must be used within a functional component that is wrapped by the FliptProvider context. A default value is returned if the feature flag cannot be evaluated at the current time (e.g., due to network issues or missing data).

import { useFliptVariant } from '@flipt-io/flipt-client-react';

function MyComponent() {
  const result = useFliptVariant('my-flag', 'fallback', 'user-123', {
    // additional context
  });
  const handleCheckFlag = async () => {
    console.log('Flag evaluation result:', result);
  };

  return (
    <div>
      <button onClick={handleCheckFlag}>Check Flag</button>
    </div>
  );
}

useFliptSelector Hook

The useFliptSelector hook allows direct access to the Flipt client so that it can be used in a functional component that is wrapped in a FliptProvider.

This is useful for more complex evaluations or in cases where you wish to call other methods on the Flipt client.

[!WARNING] flipt-client-react heavily depends on the useSyncExternalStore hook which has some caveats

import { useFliptSelector } from '@flipt-io/flipt-client-react';

function MyComponent() {
  const result = useFliptSelector((client, isLoading, error) => {
    const result = client?.evaluateBoolean('my-flag', 'user-123', {
      // additional context
    });
    console.log('Flag evaluation internals:', result, isLoading, error);
    return result?.enabled;
  });

  // Use the client to evaluate flags
  const handleCheckFlag = async () => {
    console.log('Flag evaluation result:', result);
  };

  return (
    <div>
      <button onClick={handleCheckFlag}>Check Flag</button>
    </div>
  );
}

Initialization Arguments

The FliptProvider component accepts two optional arguments:

  • namespace: The namespace to fetch flag state from. If not provided, the client will default to the default namespace.
  • options: An instance of the ClientOptions type that supports several options for the client. The structure is:
    • url: The URL of the upstream Flipt instance. If not provided, the client will default to http://localhost:8080.
    • authentication: The authentication strategy to use when communicating with the upstream Flipt instance. If not provided, the client will default to no authentication. See the Authentication section for more information.
    • updateInterval: The polling interval for fetching new state from Flipt. Set to 120 seconds by default. A 0 value disables polling completely after the initial fetch.
    • reference: The reference to use when fetching flag state. If not provided, reference will not be used.
    • fetcher: An implementation of a fetcher interface to use when requesting flag state. If not provided, a default fetcher using the browser's fetch API will be used.

Authentication

The FliptProvider component supports the following authentication strategies:

Examples

Here's a more complete example of how to use the Flipt React SDK in your application:

import React from 'react';
import { FliptProvider, useFliptBoolean } from '@flipt-io/flipt-client-react';

// A custom component that renders its children if the feature flag is enabled
function FeatureFlag({ flagKey, entityId, children }) {
  const isEnabled = useFliptBoolean('flagKey', false, entityId, {
    // additional context
  });
  return isEnabled ? children : null;
}

function App() {
  return (
    <FliptProvider options={{ url: 'https://your-flipt-instance.com' }}>
      <h1>My App</h1>
      {/* Will render the children if the feature flag evaluation results in true */}
      <FeatureFlag flagKey="new-feature" entityId="user-123">
        <div>This is a new feature!</div>
      </FeatureFlag>
    </FliptProvider>
  );
}

export default App;

Contributing

Contributions are welcome! Please feel free to open an issue or submit a Pull Request.

License

This project is licensed under the MIT License.