Skip to content

About the author of Daydream Drift

Tomasz Niezgoda (LinkedIn/tomaszniezgoda & GitHub/tniezg) is the author of this blog. It contains original content written with care.

Please link back to this website when referencing any of the materials.

Author:

When To Avoid Higher-Order Components

Published

Using HOCs instead of Render Props doesn't have a lot of downsides. But there's one which can complicate the hierarchy of components: Providing state in a base React component to the HOC surrounding it is hard. The only way to solve this issue without breaking React's rules is to use a callback to lift state up the hierarchy. The callback may need to be provided by the HOC's parent component which then sends appropriate values down to the HOC. That is if the HOC is unable to handle the callback directly.

Render Props are easier to combine within the hierarchy of components. They can wrap React components and be surrounded by them. And all this can be setup within a single, master component.

This difference between HOCs and Render Props matters in large projects. I myself encountered this while using Formik to validate dynamic forms.

Formik provides a HOC and an equivalent Render Prop for managing forms, i.e. validating inputs, providing initial values and sending values to the server for processing. Choosing the HOC or Render Prop can have long lasting effects on the shape of the project. For most forms a HOC is enough. Over time and as forms become more complex the benefit of using the Render Prop over the HOC grows. One example feature increasing complexity is the validation of dynamically changing inputs. In e-commerce, this is required when a user switches between different delivery methods at checkout.