Blog>
Snippets

Creating a Feature Flag Toggle Action

Demonstrate how to create a Redux action that toggles the state of a feature flag, allowing for dynamic control of feature availability.
// action types
const TOGGLE_FEATURE_FLAG = 'TOGGLE_FEATURE_FLAG';
Define the action type for toggling a feature flag.

// action creator
const toggleFeatureFlag = (featureName) => ({
    type: TOGGLE_FEATURE_FLAG,
    payload: featureName
});
Create an action creator function that returns an action object with the type and the name of the feature flag to toggle.

// reducer
const featureFlagsReducer = (state = {}, action) => {
    switch (action.type) {
        case TOGGLE_FEATURE_FLAG:
            return {
                ...state,
                [action.payload]: !state[action.payload]
            };
        default:
            return state;
    }
};
Define a reducer that listens for the toggle feature flag action and toggles the flag's state. The state object holds the current flags and their boolean states.