Skip to content

When HOC shines

Daisho Komiyama edited this page Jun 22, 2022 · 4 revisions

I had been skeptical about how useful HOC can be in React.

But maybe this is when HOC really shines: RBAC (Role-Based-Access-Control)

It helps us keep fewer conditions (if) out of our code.

HOC with two steps

  1. Preparation: create HOC and a component
export const withRole = roles => Component => props => {
  const userRole = useSelector(getUserRole) // fetches user role from redux store for example
  // or maybe we can do this `const { userRole } = props`

  if (roles.includes(userRole)) {
    return <Component {...props} />
  }
  return null
}

export const Button = ({ onClick, text }) => (
  <button onClick={onClick}>text</button>
)
  1. Consuming HOCs in another component. Assuming the user is a manager.
const RestrictedButton = withRole(['admin', 'manager'])(Button)
const RegularButton = withRole(['editor'])(Button)

return (
  <div>
    <RestrictedButton text='Approve' onClick={...} /> // rendered
    <RegularButton text='Request approval' onClick={...} /> // not rendered
  </div>
)

We can reuse HOC with any components.

const RestrictedContent = withRole(['adult'])(SomeContent)
const RegularContent = withRole(['adult', 'child'])(SomeContent)

// assuming the user is child
return (
  <div>
    <RestrictedContent text='Violent text' /> // not rendered
    <RegularContent text='Boring text' /> // rendered
  </div>
)
Clone this wiki locally