The Current State of HoC, Hooks, and Render Props

In 2021 React hooks are everywhere and many serious OSS projects are using functional components … Read more The Current State of HoC, Hooks, and Render Props

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

During ReactEurope Erik Rasmussen[1] 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()[2] function from React Redux used to connect your component to the store. It does return a HoC.


connect()(MyComponent);

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 more useful for production apps. The main reason is… testing. It’s very easy to test a component that gets all its data via props.

function MyComponent({
  name,           
  size,           
  count,            activateAction  });

With the hooks your tests won’t be that straightforward as per some tradeoffs[3].

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[4]. Collaboration, testing, reusability, and logic explicitness, should determine what would be a better fit and not the mainstream.

References

  1. ^ Erik Rasmussen (twitter.com)
  2. ^ connect() (react-redux.js.org)
  3. ^ per some tradeoffs (blog.isquaredsoftware.com)
  4. ^ hooks are not always your silver bullet (webup.org)


Source: Echo Js


Categories: Development, Software


Leave a Reply

Your email address will not be published. Required fields are marked *