High-order components (HOCs) are a fascinating feature in React, enabling the reusability of components with similar logic. Despite sounding abstract and advanced, this pattern is not specific to React and can be applied in various scenarios. For instance, you can use HOCs to add loading indicators to components without modifying the original code or hide properties for cleaner interfaces. This tutorial AIms to cover many such applications, as most existing resources cater to experienced React developers.
The article is divided into three parts. The first part introduces the concept of HOCs, discussing syntax needed to understand them, particularly high-order functions. In the second part, the excitement builds as you’ll witness a practical HOC example, using it to create forms, authorization, and more. The third part focuses on best practices and considerations when implementing HOCs, briefly touching upon alternative code-sharing patterns like render props.
Before diving in, it’s recommended to have a grasp on stateful and stateless components in React for better understanding of the component architecture. Familiarity with ES6 syntax will also be beneficial, as it pairs well with HOCs. If you’re new to ES6, a quick review might be helpful.
### Arrow Functions
Arrow functions are shorthand for regular function expressions, ideal for non-method functions, which we’ll focus on. Here are some examples to get you started:
1. **No Parameters**:
“`javascript
// Regular function expression
function() {
return “This is a function expression”;
}
// Equivalent arrow function
() => “This is a shorter arrow function”
“`
2. **Single Parameter**:
“`javascript
// Regular function expression
function(param) {
return { title: “This function accepts a parameter and returns an object”, params: param };
}
// Equivalent arrow function
param => ({ title: “This arrow function accepts a single parameter”, params: param })
“`
3. **Multiple Parameters**:
“`javascript
// Regular function expression
function(param1, param2) {
return { title: “This function accepts multiple parameters”, params: param1 + param2 }; // Using the spread syntax
}
// Equivalent arrow function
(param1, param2) => ({ title: “This arrow function accepts multiple parameters”, params: param1 + param2 })
“`
Now that the theory is out of the way, let’s look at some code. Below is a simple example that wraps an input component with a gray background:
“`javascript
// The “with” prefix in the function name is a naming convention. You can name it anything meaningful.
const withGreyBG = WrappedComponent => class NewComponent extends Component {
const bgStyle = { backgroundColor: ‘grey’ };
render() {
return (
);
}
};
const SmallCardWithGreyBG = withGreyBG(SmallCard);
const BigCardWithGreyBG = withGreyBG(BigCard);
const HugeCardWithGreyBG = withGreyBG(HugeCard);
class CardsDEMO extends Component {
render() {
return (
);
}
}
The `withGreyBG` function takes a component as input and returns a new one. Instead of indiVidually styling each card component, we create a hoc to handle this task. HOCs wrap the original components and add enhancements.
While this may not seem particularly useful now, its benefits become apparent in more complex scenarios. Consider protecting routes with authentication in a React Router setup. Instead of repeating authentication code, we can effectively manage protected routes using HOCs. Intrigued? Stay tuned for the next tutorial where we explore this and more.
Note: ECMAScript introduced decorators, making HOC usage easier, but it’s still experimental. In this tutorial, we’ll stick to the standard approach. If you’re using `create-react-app`, ensure you’ve disabled decorator support if necessary.
In this tutorial, we’ve covered the basics of HOCs. They’re a popular technique for building reusable components. We beGAN by discussing essential ES6 syntax, then moved on to high-order functions and their workings, and finally created an HOC from scratch.
In the following section, we’ll dive into different HOC techniques with practical examples. Keep an eye out, and feel free to share your thoughts in the comments.