DEV Community

Rafi
Rafi

Posted on • Edited on

4 1

Simple hook to handle featue flags

Let's say you want to enable or disable some features based on users role or some permission that the user is granted in the frontend. You could do this with a simple conditional rendering in each component by checking for users permission

<div>
 {role==='guest' && <GuestBanner/>}
</div>
Enter fullscreen mode Exit fullscreen mode

But this is really messy if you have to do this in multiple components. We could instead create a custom hook that returns Boolean saying if we should enable or disable the feature

import { useSelector } from 'react-redux';

const useFeature = (feature) => {

 // If you use something other than redux replace useSelector with equivalent
// getRole is selector to select user role from redux state
const role = useSelector(getRole)

if(feature === 'guestBanner') {
  if(role === 'guest') return true;

  return false;
}

return true;

}
Enter fullscreen mode Exit fullscreen mode

And then in your component you use this as follows

import useFeature from './use-feature';

const GuestBanner = () => {
  const enable = useFeature('guestBanner');

  if(!enable) return null;

   return <h1>Guest Banner</h1>

}
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →