React Higher Order Component


1.Introduction:

  • A higher-order component (HOC) is an advanced technique in React for reusing component logic. Concretely, a higher-order component is a function that takes a component and returns a new component. i.e wrapping around the “normal” components and provide additional data input.
const EnhancedComponent = higherOrderComponent(WrappedComponent);
  • a component transforms props into UI, a higher-order component transforms a component into another component.
  • HOCs are common in third-party React libraries, such as Redux’s connect and Relay’s createFragmentContainer.

Example:

The MyHigherHOC is a higher-order Component that is used only to pass data to MyComponent. This function takes MyComponent, enhances it with updateData, and returns the enhanced component that will be rendered on the screen.

MyHigherHOC.jsx

import React from 'react';
var updateData = {
   data: 'Data from Higher Order Component',
}

var MyHigherHOC = updateComponent => class extends React.Component {
   componentDidMount() {
      this.setState({
         data: updateData.data
      });
   }
   render() {
      return <App {...this.props} {...this.state} />;
   }
};
class App extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.data}</h1>
         </div>
      )
   }
}
export default MyHigherHOC(App);


Warning:

1.Don’t Use HOCs Inside the render method.
2.The static methods must be copied over to have access to them. You can do this using the hoist-non-react-statics package to automatically copy all non-React static methods.
3.HOCs do not work for refs as the ref is not really a prop — like a key, it’s handled specially by React.
4.If you add a ref to an element whose component is the result of a HOC, the ref refers to an instance of the outermost container component, not the wrapped component.