A Gentle Introduction to Higher-Order Components in React: Best Practices
This is the third part of the series on Higher-Order Components. In the first tutorial, we started from ground zero. We learned the basics of ES6 syntax, higher-order functions, and higher-order components.
The higher-order component pattern is useful for creating abstract components—you can use them to share data (state and behavior) with your existing components. In the second part of the series, I demonstrated practical examples of code using this pattern. This includes protected routes, creating a configurable generic container, attaching a loading indicator to a component, etc.
In this tutorial, we will have a look at some best practices and dos and don'ts that you should look into while writing HOCs.
Introduction
React previously had something called Mixins, which worked great with the React.createClass
method. Mixins allowed developers to share code between components. However, they had some drawbacks, and the idea was dropped eventually. Mixins were not upgraded to support ES6 classes, and Dan Abramov even wrote an in-depth post on why Mixins are considered harmful.
Higher-order components emerged as an alternative to Mixins, and they supported ES6 classes. Moreover, HOCs don't have to do anything with the React API and are a generic pattern that works well with React. However, HOCs have flaws too. Although the downsides of higher-order components might not be evident in smaller projects, you could have multiple higher-order components chained to a single component, just like below.
const SomeNewComponent = withRouter(RequireAuth(LoaderDemo(GenericContainer(CustomForm(Form)))))
You shouldn't let the chaining get to the point where you are asking yourself the question: "Where did that props come from?" This tutorial addresses some of the common issues with higher-order component patterns and the solutions to get them right.
The Problems With HOC
Some of the common problems concerned with HOCs have less to do with HOCs themselves, but rather your implementation of them.
As you already know, HOCs are great for code abstraction and creating reusable code. However, when you have multiple HOCs stacked up, and if something looks out of place or if some props are not showing up, it's painful to debug because the React DevTools give you a very limited clue about what might have gone wrong.
A Real-World HOC Problem
To understand the drawbacks of HOCs, I've created an example demo that nests some of the HOCs that we created in the previous tutorial. We have four higher-order functions wrapping that single ContactList component. If the code doesn't make sense or if you haven't followed my previous tutorial, here is a brief summary of how it works.
withRouter
is a HOC that's part of the react-router package. It provides you access to the history object's properties and then passes them as a prop.
withAuth
looks for an authentication
prop and, if authentication is true, it renders the WrappedComponent
. If authentication is false, it pushes '/login
' to the history object.
withGenericContainer
accepts an object as an input in addition to the WrappedComponent
. The GenericContainer
makes API calls and stores the result in the state and then sends the data to the wrapped component as props.
withLoader
is a HOC that attaches a loading indicator. The indicator spins until the fetched data reaches the state.
BestPracticeDemo.jsx
class BestPracticesDemo extends Component { render() { return( <div className="contactApp"> <ExtendedContactList authenticated = {true} {...this.props} contacts ="this" /> </div> ) } } const ContactList = ({contacts}) => { return( <div> <ul> {contacts.map( (contact) => <li key={contact.email}> <img src={contact.photo} width="100px" height="100px" alt="presentation" /> <div className="contactData"> <h4>{contact.name}</h4> <small>{contact.email}</small> <br/><small> {contact.phone}</small> </div> </li> )} </ul> </div> ) } const reqAPI = {reqUrl: 'https://demo1443058.mockable.io/users/', reqMethod:'GET', resName:'contacts'} const ExtendedContactList = withRouter( withAuth( withGenericContainer(reqAPI)( withLoader('contacts') (ContactList)))); export default BestPracticesDemo;
Now you can see for yourself some of the common pitfalls of higher-order components. Let's discuss some of them in detail.
Basic Dos and Don'ts
Don't Forget to Spread the Props in Your HOC
Assume that we have an authenticated = { this.state.authenticated }
prop at the top of the composition hierarchy. We know that this is an important prop and that this should make it all the way to the presentational component. However, imagine that an intermediate HOC, such as withGenericContainer
, decided to ignore all its props.
//render method of withGenericContainer render() { return( <WrappedComponent /> ) }
This is a very common mistake that you should try to avoid while writing higher-order components. Someone who isn't acquainted with HOCs might find it hard to figure out why all the props are missing because it would be hard to isolate the problem. So, always remember to spread the props in your HOC.
//The right way render() { return( <WrappedComponent {...this.props} {...this.state} />) }
Don't Pass Down Props That Have No Existence Beyond the Scope of the HOC
A HOC might introduce new props that the WrappedComponent might not have any use for. In such cases, it's a good practice to pass down props that are only relevant to the composed components.
A higher-order component can accept data in two ways: either as the function's argument or as the component's prop. For instance, authenticated = { this.state.authenticated }
is an example of a prop, whereas in withGenericContainer(reqAPI)(ContactList)
, we are passing the data as arguments.
Because withGenericContainer is a function, you can pass in as few or as many arguments as you like. In the example above, a config object is used to specify a component's data dependency. However, the contract between an enhanced component and the wrapped component is strictly through props.
So I recommend filling in the static-time data dependencies via the function parameters and passing dynamic data as props. The authenticated props are dynamic because a user can be either authenticated or not depending on whether they are logged in or not, but we can be sure that the contents of the reqAPI
object are not going to change dynamically.
Don’t Use HOCs Inside the Render Method
Here is an example that you should avoid at all cost.
var OriginalComponent = () => <p>Hello world.</p>; class App extends React.Component { render() { return React.createElement(enhanceComponent(OriginalComponent)); } };
Apart from the performance hitches, you will lose the state of the OriginalComponent
and all of its children on each render. To solve this problem, move the HOC declaration outside the render method so that it is only created once, so that the render always returns the same EnhancedComponent.
var OriginalComponent = () => <p>Hello world.</p>; var EnhancedComponent = enhanceComponent(OriginalComponent); class App extends React.Component { render() { return React.createElement(EnhancedComponent); } };
Don't Mutate the Wrapped Component
Mutating the Wrapped Component inside a HOC makes it impossible to use the Wrapped Component outside the HOC. If your HOC returns a WrappedComponent, you can almost always be sure that you're doing it wrong. The example below demonstrates the difference between mutation and composition.
function logger(WrappedComponent) { WrappedComponent.prototype.componentWillReceiveProps = function(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); }; // We're returning the WrappedComponent rather than composing //it return WrappedComponent; }
Composition is one of React's fundamental characteristics. You can have a component wrapped inside another component in its render function, and that's what you call composition.
function logger(WrappedComponent) { return class extends Component { componentWillReceiveProps(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); } render() { // Wraps the input component in a container, without mutating it. Good! return <WrappedComponent {...this.props} />; } } }
Moreover, if you mutate the WrappedComponent inside a HOC and then wrap the enhanced component using another HOC, the changes made by the first HOC will be overridden. To avoid such scenarios, you should stick to composing components rather than mutating them.
Namespace Generic Propnames
The importance of namespacing prop names is evident when you have multiple stacked up. A component might push a prop name into the WrappedComponent that's already been used by another higher-order component.
import React, { Component } from 'react'; const withMouse = (WrappedComponent) => { return class withMouse extends Component { constructor(props) { super(props); this.state = { name: 'Mouse' } } render() { return( <WrappedComponent {...this.props} name={this.state.name} /> ); } } } const withCat = (WrappedComponent) => { return class withCat extends Component { render() { return( <WrappedComponent {...this.props} name= "Cat" /> ) } } } const NameComponent = ({name}) => { return( <div> {name} </div>) } const App =() => { const EnhancedComponent = withMouse(withCat(NameComponent)); return( <div> <EnhancedComponent /> </div>) } export default App;
Both the withMouse
and withCat
are trying to push their own version of name prop. What if the EnhancedComponent too had to share some props with the same name?
<EnhancedComponent name="This is important" />
Wouldn't it be a source of confusion and misdirection for the end developer? The React Devtools don't report any name conflicts, and you will have to look into the HOC implementation details to understand what went wrong.
This can be solved by making HOC prop names scoped as a convention via the HOC that provides them. So you would have withCat_name
and withMouse_name
instead of a generic prop name.
Another interesting thing to note here is that ordering your properties is important in React. When you have the same property multiple times, resulting in a name conflict, the last declaration will always survive. In the above example, the Cat wins since it's placed after { ...this.props }
.
If you would prefer to resolve the name conflict some other way, you can reorder the properties and spread this.props
last. This way, you can set sensible defaults that suit your project.
Make Debugging Easier Using a Meaningful Display Name
The components created by a HOC show up in the React Devtools as normal components. It's hard to distinguish between the two. You can ease the debugging by providing a meaningful displayName
for the higher-order component. Wouldn't it be sensible to have something like this on React Devtools?
<withMouse(withCat(NameComponent)) > ... </withMouse(withCat(NameComponent))>
So what is displayName
? Each component has a displayName
property that you can use for debugging purposes. The most popular technique is to wrap the display name of the WrappedComponent
. If withCat
is the HOC, and NameComponent
is the WrappedComponent
, then the displayName
will be withCat(NameComponent)
.
const withMouse = (WrappedComponent) => { class withMouse extends Component { /* */ } withMouse.displayName = `withMouse(${getDisplayName(WrappedComponent)})`; return withMouse; } const withCat = (WrappedComponent) => { class withCat extends Component { /* */ } withCat.displayName = `withCat(${getDisplayName(WrappedComponent)})`; return withCat; } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; }
An Alternative to Higher-Order Components
Although Mixins are gone, it would be misleading to say higher-order components are the only pattern out there that allow code sharing and abstraction. Another alternative pattern has emerged, and I've heard some say it's better than HOCs. It's beyond the scope of this tutorial to touch on the concept in depth, but I will introduce you to render props and some basic examples that demonstrate why they are useful.
Render props are referred to by a number of different names:
- render prop
- children prop
- function as a child
- render callback
Here is a quick example that should explain how a render prop works.
class Mouse extends Component { constructor() { super(); this.state = { name: "Nibbles" } } render() { return( <div> {this.props.children(this.state)} </div> ) } } class App extends Component { render() { return( <Mouse> {(mouse) => <div> The name of the mouse is {mouse.name} </div> } </Mouse> ) } }
As you can see, we've got rid of the higher-order functions. We have a regular component called Mouse
. Instead of rendering a wrapped component in its render method, we are going to render this.props.children()
and pass in the state as an argument. So we are giving Mouse
a render prop, and the render prop decides what should be rendered.
In other words, the Mouse
components accept a function as the value for the children props. When Mouse
renders, it returns the state of the Mouse
, and the render prop function can use it however it pleases.
There are a few things I like about this pattern:
- From a readability perspective, it's more evident where a prop is coming from.
- This pattern is dynamic and flexible. HOCs are composed at static-time. Although I've never found that to be a limitation, render props are dynamically composed and are more flexible.
- Simplified component composition. You could say goodbye to nesting multiple HOCs.
Conclusion
Higher-order components are patterns that you can use to build robust, reusable components in React. If you're going to use HOCs, there are a few ground rules that you should follow. This is so that you don't regret the decision of using them later on. I've summarized most of the best practices in this tutorial.
HOCs are not the only patterns that are popular today. Towards the end of the tutorial, I've introduced you to another pattern called render props that is gaining ground among React developers.
I won't judge a pattern and say that this one is better than another. As React grows, and the ecosystem that surrounds it matures, more and more patterns will emerge. In my opinion, you should learn them all and stick with the one that suits your style and that you're comfortable with.
This also marks the end of the tutorial series on higher-order components. We've gone from ground zero to mastering an advanced technique called HOC. If I missed anything or if you have suggestions/thoughts, I would love to hear them. You can post them in the comments.
from Envato Tuts+ Tutorials
Comments
Post a Comment