If you are working with React, you might have heard of the term higher-order component or HOC. But what does it mean and why is it useful? In this article, I will try to explain the concept of HOCs in a simple and beginner-friendly way. I will also give a brief introduction to system design for frontend developers.
What is a higher-order component?
Components are the building blocks of React applications. They allow us to break down complex UIs into smaller and simpler parts that can be reused and composed together.
A higher-order component (HOC) is a function that takes a component as an argument and returns a new component. It is a way of enhancing or modifying the behavior or appearance of an existing component without changing its source code. For example, here is a HOC that adds a border around any component:
function withBorder(WrappedComponent) {
return function (props) {
return (
<div style={{ border: "2px solid green" }}>
<WrappedComponent {...props} />
</div>
);
};
}
The withBorder function takes a component (WrappedComponent) and returns another component that renders the original component inside a div with a border style. The returned component also passes down any props it receives to the wrapped component using the spread operator {...props}.
Assume a basic react component which says adds Hello,
before passes prop (name)
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
The following picture shows rendering of before and after wrapping a component with a higher order component (HOC)
Advantages of using HOCs
- They promote code reuse and avoid duplication. Instead of writing the same logic or style in multiple components, we can extract it into a HOC and apply it to any component we want.
- They separate concerns and enhance readability. Instead of mixing different aspects of functionality or appearance in one component, we can separate them into different HOCs and compose them together.
- They follow the principle of composition over inheritance. Instead of creating complex class hierarchies to inherit behavior or appearance from parent components, we can use simple functions to compose components together.
Some best practices and conventions to follow when writing HOCs:
- Use descriptive names that start with
with
. This makes it clear that the function is a HOC and what it does. For example,withBorder
,withLoading
,withData
, etc. - Pass down all props to the wrapped component. This ensures that the HOC does not interfere with the props that the wrapped component expects or needs. Use the spread operator
{...props}
to pass down all props easily. - Do not mutate or modify the wrapped component. This can cause unexpected side effects and break the component. Instead, create a new component that wraps the original component and adds the desired functionality or appearance.
Top comments (0)