Use of Higher Order Component (Hoc) in React
A Higher Order Component(HOC) is a function that takes a component and returns a new component.
Higher Order Component (HOC) is used for reuse component code and logic.
Higher order component use for reduce lots of duplicate code, we can write once and make wrapper for the other component. Redux `Connect()` method will be example of higher order component, where we are connecting ReduxStore with the component.
Example1:
import React from 'react';export const HigherOrderComponent = WrappedComponent =>
class HOC extends React.Component {
render() {
return <WrappedComponent />
}
};
Example2:
export class HocComponent extends React.Component {
render() {
return (
<View>
<Header></Header>
<View>{this.props.children}</View>
<Footer></Footer>
</View>
) }
}
Use of higher order component like below:
export const SimpleHOC = HigherOrderComponent(MyComponent);
or
export class SomeComponent extends React.Component {
return () {
<HocComponent>
<View>
<Text> This is a Component </Text>
</View>
</HocComponent>
}
}
Higher order component takes another component as argument and it will return new component, HOC also used to using common logic for the multiple component or screen, Like Event subscription for the keyboard hide or show, So for that we need to make HOC with the keyboard listener, So we can use same logic in multiple places.
If want to know more about HOC, here is a React official document: https://reactjs.org/docs/higher-order-components.html