Reusable React Permission HOC

I wanted to share a design pattern I use to manage what certain users can or cannot see inside the React applications I build.

You might find this useful if your application needs to manage what users can see based on some setting in their account.

The example I’m going to show has several different components working together:

  1. React for the UI component library
  2. Typescript for type safety
  3. Redux for global state management
  4. Bitmask for users permissions

To start, let’s say you have a simple component with some text that you want to show or hide based on a users permission:

A simple way to do this would be to check a users permission level on a case by case basis.

Note: in the examples below I use the bitwise AND operator (&) to check my permission. The operation will produce either 1 or 0. Substitute your own check if your permissions model is different.

This example works, but as the application grows, always having to get the users status can add to the complexity of the page.

To solve this for myself, I created a Higher Order Component that wraps each block of sensitive information and requires one argument for the permission to check against. The component handles the status check and the show / hide logic.

Note: This example works best if you are using some kind of global state provider in your application.

Now I can wrap any sensitive information with this component and supply the relevant permission to check against.

Former golf instructor turned software engineer. 4 years ago I left my job teaching golf in Beijing to pursue my passion for writing code.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store