How to use HOC

Tomoharu Tsutsumi
2 min readJun 29, 2019

--

What is HOC?

HOC is Higher-Order-Component. The instructions below is from the document of React.

a higher-order component is a function that takes a component and returns a new component.Quote https://reactjs.org/docs/higher-order-components.html

HOC takes component as arguments and returns component. However, I think an example is necessary, so I show it below.

Example

This code is the example.

import React from 'react';import ReactDOM from 'react-dom';const Info = (props) => (  <div>    <h1>Info</h1>     <p>The info is: {props.info}</p>  </div>);
const ComponentA = (WrappedComponent) => { return (props) => ( <div> {props.isAdmin && <p>this is private info</p>} <WrappedComponent {...props}/> </div> )};const ComponentB = (WrappedComponent) => { return (props) => ( <div> {props.isAuthenticated ? <WrappedComponent {...props}/> : <p>please login</p> } </div> )}const AdminInfo = ComponentA(Info);const AuthInfo = ComponentB(Info);ReactDOM.render(<AdminInfo isAdmin={true} info="details"/>, document.getElementById('root'))

In this case, ComponentA and ComponentB are HOC. The argument is Info component. They takes Info component as an argument and returns component. ReactDOM displays returned component.

Firstly, AdminInfo component takes props(isAdmin, info). The props are send to ComponentA and ComponentA can access to the props. Wrapped Component is Info Component. Also, the props are send to Info Component , and Info Component can deal with those props. If I change my codes, what will happen? I coded above…

ReactDOM.render(<AdminInfo isAdmin={true} info="details"/>, document.getElementById('root'))

However, I change that code to below.

ReactDOM.render(<AuthInfo isAuthenticated={true} info="details"/>, document.getElementById('root'))

Yes, displayed component changes. Also, the only one prop changes too. The prop is isAuthenticated. However, info prop is not changed. The prop info can be used in ComponentA and ComponentB because ComponentA and ComponentB can access to Info Component.

Why should we use HOC?

I hope you understand how to use HOC, but what is good? The greatest merit is to make a function common among components. You don’t have to code the same function. Also, you can use the component again in other places. The code becomes cleaner and more understandable.

If you think this article good, please follow me!

https://twitter.com/tomoharutsutsum

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

5+ years Full Stack SWE (Ruby, Go, TypeScript, JavaScript) | Former Founding Engineer of AI Startup in Canada

No responses yet