A Higher-Order Component (HOC) in React is a 'component that returns another component'. This technique is derived from the higher-order functions concept in JavaScript, where a function can take another function as an argument and/or return a function.
Higher-Order Components are an advanced technique in React for reusing component logic, and HOCs are not part of the React API, they are a pattern that emerges from the compositional nature of React.
In simple terms, a Higher-Order Component (HOC) is a function that takes a component and returns a new component. It could be described with the following signature in JavaScript:
function withComponent(WrappedComponent) {
return class extends React.Component {
render() {
return <WrappedComponent {...this.props} />;
}
};
}
In this basic example, withComponent
is a higher-order component that takes WrappedComponent
as an argument and returns a new component that renders WrappedComponent
.
One of the primary uses of HOC is to abstract shared logic across multiple components. This can lead to more readable and maintainable code because it allows developers to follow the 'Don't Repeat Yourself' (DRY) principle.
Consider a scenario where you have several components that should fetch data from an API and render the retrieved data. Instead of implementing the fetching logic in each component, you can create a withData
HOC that handles the fetching and passes the data as props to the wrapped components.
function withData(WrappedComponent, url) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(data => this.setState({ data: data }));
}
render() {
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}
While HOCs provide a powerful way to abstract common behavior, there are some best practices that developers should keep in mind:
Understanding Higher-Order Components in React goes a long way toward writing more efficient, maintainable, and reusable components, which are important aspects of scalable React applications.