Introduction
Explore how higher order components enable reusable component logic in React by wrapping components with added functionality. Understand the distinction between smart components handling business logic and dumb components focusing on display. This lesson helps you grasp component organization for cleaner, modular React applications.
We'll cover the following...
What are higher order components?
Higher order components (or HOC or HOCs for short) were, and still are, a central concept in React. They allow you to implement components with reusable logic and are loosely tied to higher order functions from functional programming. These kinds of functions take a function as a parameter and return another function. In terms of React, this principle is applied to components. HOCs derive their name from those higher order functions.
Let us look at an example to illustrate this concept better:
const withFormatting = (WrappedComponent) => {
return class extends React.Component {
bold = (string) => {
return <strong>{string}</strong>;
};
italic = (string) => {
return <em>{string}</em>;
};
render() {
return <WrappedComponent bold={this.bold} italic={this.italic} />;
}
};
};
We have defined a function called withFormatting that takes in a React component. The function will return a new React component, which in turn renders the passed component and equips it with the props bold and italic. The component can now access these props:
const FormattedComponent = withFormatting(({ bold, italic }) => (
<div>
This text is {bold('bold')} and {italic('italic')}.
</div>
));
Let’s see and run this example interactively.
import React from 'react';
import ReactDOM from 'react-dom';
import util from './app.js';
require('./style.css');
const App = util.withFormatting(util.FormattedComponent);
ReactDOM.render(
<App />,
document.getElementById('root')
);
Smart and dumb components
Typically, higher order components can be used to encapsulate logic. They relate closely to the concept of smart and dumb components. Smart components (which also encompass HOCs) are used to:
- Display business logic
- Deal with API communication
- Deal with behavioral logic
Dumb components, in contrast, are usually passed static props and keep logic to a minimum (which is only used for display logic). For example, it might decide whether to show a profile image or, if it is not present, show a placeholder image instead. Sometimes, we also refer to container components (for smart components) and layout components (for dumb components).
But why do we categorize components this way? This strict divide into business logic and display logic enables component-based development. It allows us to create layout components that do not know of possible API connections and only display data that is passed to them, no matter where it comes from. It also enables the business logic components to only concern themselves with business logic without caring about how the data is displayed in the end.