English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Higher Order Component is a JavaScript function used to add additional features to existing components. These functions are pure functions, which means they receive data and return values based on that data. If the data changes, the higher-order function will re-run using different data inputs. If we want to update the returned component, we do not need to change the HOC. All we need to do is change the data the function is using.
Higher Order Component (HOC) wraps around 'normal' components and provides additional data inputs. It is actually a function that accepts a component and returns another component that wraps the original component.
Let's look at a simple example to understand how this concept works. MyHOC is a higher-order function that is used solely to pass data to MyComponent. The function accepts MyComponent, enhances it with newData, and returns the enhanced component that will be rendered on the screen.
import React from 'react'; var newData = { data: 'Data from HOC...' } var MyHOC = ComposedComponent => class extends React.Component { componentDidMount() { this.setState({ data: newData.data }); } render() { return <ComposedComponent {...this.props} {...this.state}> /}; } }; class MyComponent extends React.Component { render() { return ( <div> <h1>{this.props.data}<//h1> </div> ) } } export default MyHOC(MyComponent);
If we run the application, we will see that the data has been passed toMyComponent.
NoteHigher-order components can be used for different functionalities. These pure functions are the essence of functional programming. Once you get used to them, you will notice that your application becomes increasingly easier to maintain or upgrade.