TECH Insights

Viden og indsigter fra IT Minds' it-talenter

Higher-Order Components in React, when and why

Skrevet af Mindster og Software Developer hos IT Minds on 18-07-19 10:34
Mindster og Software Developer hos IT Minds

Higher-Order Components (HOCs) in React is a way of introducing reusability for component logic to stay DRY. Sounds good so let's just get started using using HOCs. Now wait a minute, before you start to introduce HOCs in your app there are some downsides to all this generic goodness.

Currently i am working on a large scale platform written in React and React-Native. The React-Native app is centered around the user, and the React app is centered around controlling the content shown in the app and managing users connected to the platform.

The web platform has grown a lot throughout the year i have been working on it and is now 300000+ lines of code.

From the start of the development there has been a drive around creating generic reusable components to stay DRY. While this is in essence very good, we have found, through the development, that sometimes the genericness of our code would shoot us in the foot.

We originally intended our HOCs to handle all data access to our API so we could separate it from our view logic. While this in essence was a good idea, it introduced some unintended side effects, since parameterized data access was handled with extra props in our HOCs and destroyed the composable nature of HOCs, as more than one HOC could require the same parameters, and these would not get parsed through.

The convention when writing a HOC with props is

Screenshot 2019-07-18 at 10.26.30

Wan't to see the code-snippet? Read the blogpost on here.

which removes the extra props required by the HOC and pass the rest to the Wrapped Component. But what if you compose two or more HOCs that all require extraProp, like so

Screenshot 2019-07-18 at 10.27.09

only the first HOC will ever get the extra props.

Instead of this approach one could move the responsibility of getting the extra props, to the Wrapped Component like so

Screenshot 2019-07-18 at 10.28.33

this allows the HOCs to be composable even if they require the same extra props, but it moves the responsibility to the wrapped component, which of course is a trade off.

Insights fra de bedste softwaretalenter

En del af IT Minds’ DNA er, at vi spotter og tiltrækker de bedste softwaretalenter, som er stærke i de nyeste teknologier og frameworks. Derfor vil vi gerne dele ud af vores viden og erfaringer vores konsulenter opsamler, når de afprøver og arbejder med nye teknologier og frameworks.

Seneste indlæg