
what is Custom Higher-Order Components (HOC) ?
A Higher-Order Component is a function that takes a component and returns a new component with enhanced or additional behavior. Think of it as a wrapper that adds features to a component without modifying the original one.
Basic Syntax:
const withSomething = (WrappedComponent) => {
return function EnhancedComponent(props) {
// logic or props manipulation here
return <WrappedComponent {...props} />;
};
};
Why Use HOCs?
Purpose | Examples |
---|---|
Code reuse | Add logic to multiple components |
Cross-cutting logic | Authentication, loading, logging, etc. |
Abstraction | Keeps components focused on rendering |
Example: Intro to Custom HOC
withMessage.js
const withMessage = (WrappedComponent) => {
return function EnhancedComponent(props) {
const newMessage = "Message from HOC";
return <WrappedComponent {...props} message={newMessage} />;
};
};
export default withMessage;
UserComponent.js
import withMessage from './withMessage';
function User({ message }) {
return <h2>{message}</h2>;
}
export default withMessage(User);
Now, the User component receives the message via HOC without managing it itself.
Loading HOC (Loader While Data Is Fetching)
Step 1: Create a Loader HOC
const withLoader = (WrappedComponent) => {
return function WithLoaderComponent({ isLoading, ...props }) {
if (isLoading) {
return <p>Loading...</p>;
}
return <WrappedComponent {...props} />;
};
};
export default withLoader;
Step 2: Use the HOC
function App() {
const [loading, setLoading] = useState(true);
const [items, setItems] = useState([]);
useEffect(() => {
setTimeout(() => {
setItems(['React', 'Vue', 'Angular']);
setLoading(false);
}, 2000);
}, []);
return (
<div>
<h1>Frontend Frameworks</h1>
<DataListWithLoader isLoading={loading} data={items} />
</div>
);
}
Summary
Term | Meaning |
---|---|
HOC | Function that wraps and returns a new enhanced component |
Custom HOC | Add reusable logic (e.g., data, auth, props) |
withLoader | HOC that conditionally shows a loader |
Usage | Pass props, use conditional rendering |
Comments
Add new comment