Handling Feature Flags with a React Hook

Christian Förg

Motivation

Recently, we introduced a feature flag management system into our project. And since feature flags are among others used to display or hide features in the frontend, we had to find a good and uniform way to deal with them in our React components.

Write a hook

We currently started to write function components and use hooks inside them. To get more comfortable using React hooks, it was time we write one ourselves.

1
2
3
4
export function useFeature(feature: Feature) {
const features = useSelector((state: State) => state.user.features);
return features.indexOf(feature) !== -1;
}

The hook itself depends on a the useSelector hook from react-redux, because we store the feature flags in a redux state. Of course you can do that differently if you don’t use redux. The idea behind writing this hook is simply to access feature flags always in the same way, and therefore adjustments on the functionality only have to be made at one dedicated place in the code.

Let’s say you’re currently developing a page that will display the customer’s documents. All you have to do in your component is call the useFeature hook with the flag your feature is depending on. We decided to store the feature flags in an enum. However you can also consider string literal types or – if you don’t use static typings – plain old strings.

1
2
3
4
5
6
export function ExampleComponent() {
const hasDocumentView = useFeature(Feature.DocumentView);
return (
<React.Fragment>{hasDocumentView ? <DocumentView /> : null}</React.Fragment>
);
}

Conclusion

Invoking the useFeature hook feels quite natural. If you add/rename/delete a feature flag, TypeScript will support by providing suggestions or highlighting type errors. You will have a single source of truth for your features. And also features with variants would be possible with a hook. Your hook could return a tuple with the first element representing if the feature is active and the second element containing the attributes of the variant.

  • page 1 of 1