DEV Community

Cover image for React HoC vs Hooks vs Render Props in 2021
Miroslav Nikolov
Miroslav Nikolov

Posted on • Edited on • Originally published at webup.org

React HoC vs Hooks vs Render Props in 2021

Did React hooks took over or there is still room for the HoC and render prop patterns?


In 2021 React hooks are everywhere and many serious OSS projects are using functional components already.

During ReactEurope Erik Rasmussen did a good round-up of how things started with HoCs, went through their replacement — render props — and ended up today with hooks. It also compares several use cases.

If I have to make my own conclusion it would sound like that:

HoC, hooks and render props have their own use cases and none of them is a full replacement of the others. In some cases HoCs and components with a render prop my even make more sense.

A good example of the above is the connect() function from React Redux used to connect your component to the store. It does return a HoC.

// This will return a HoC wrapper around MyComponent
connect()(MyComponent);
Enter fullscreen mode Exit fullscreen mode

With the modern Redux you can get data and dispatch actions to the store directly using the useSelector and useDispatch hooks, so connect() is no longer required. While it's true, this is one of these moments where I find the HoC pattern still useful for production apps. The main reason is... testing. It's very easy to test a component in isolation via props.

function MyComponent({
  name,           // own prop
  size,           // own prop
  count,          // redux store selector
  activateAction  // redux action
});
Enter fullscreen mode Exit fullscreen mode

With the hooks your tests won't be that straightforward as per some tradeoffs but this is the recommended way to go in the React community.

To wrap up: Functional components and react hooks are our preferred way of working with React these days but hooks are not always your silver bullet. Collaboration, testing, reusability, and logic explicitness, should determine what is a better fit and not the mainstream.


Top comments (0)