React JS Higher Order Components

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

Why higher order components?

To share common functionality between components.

Let's discuss one example.

We have one component ParentComponent. ParentComponent have two child component ChildComponent1 and ChildComponent2. ChildComponent2 have one child component ChildComponent21. Now, ChildComponent1 and ChildComponent21 both have common function required. then passing this function from props ParentComponent to last child component is not proper solution. So, We can achive this things by higher order components

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

1. withCounter

withCounter
import React, { Component } from 'react'; const withCounter = WrappedComponent => { class WithCounter extends React.Component{ constructor(props) { super(props) this.state = { count: 0 } } incrementCount() { this.setState( prevState => { return { count : prevState + 1} }) } return () { return <WrappedComponent count={this.state.count} incrementCount={this.incrementCount} /> } } return WithCounter; } export default withCounter;

1. ChildComponent1

ChildComponent1
import React, { Component } from 'react'; import withCounter from './withCounter'; class ChildComponent1 extends Component { render() { const { count, incrementCount } = this.props; return( <div> <button onClick={incrementCount}>Clicked {count} times</button> </div> ); } } export default withCounter(ChildComponent1);

In above code, Our HOC component inject count and incrementCount to WrappedComponent. which we passed as withCounter(ChildComponent1); HOC component accepts ChildComponent1 as a parameter and return new component. withCounter can be used in ChildComponent21 which we discuss at the beginning of this tutorial. HOC share incrementCount between components.

 

← Previous

Next →