Shiv Upadhyay’s Post

Day 23: Higher Order Components (HOC) in React If you want to write reusable and scalable React code, you must understand this concept: 👉 Higher Order Components (HOC) This is also a popular React interview question. 📌 What is a Higher Order Component? A Higher Order Component (HOC) is a function that: ✅ takes a component as input ✅ returns a new enhanced component as output In simple words: 👉 HOC = Component that wraps another component to add extra features 📌 Why do we use HOC? Sometimes we want to reuse the same logic across multiple components like: • Authentication check • Logging • Loading spinner • Permissions • Data fetching Instead of repeating code, we use HOC. 📌 Example of HOC function withLogger(WrappedComponent) { return function EnhancedComponent(props) { console.log("Component Rendered:", WrappedComponent.name); return <WrappedComponent {...props} />; }; } 📌 Using the HOC function Profile() { return <h1>Profile Page</h1>; } export default withLogger(Profile); Now every time Profile renders, it logs automatically. 📌 Key Point ✅ HOC does not modify the original component It creates a new component with added functionality. 📌 Real-world Example Many libraries use HOC internally, like: • Redux (connect) • Authentication wrappers • Role-based UI access 📌 Interview Line 👉 HOC is used for code reusability and logic sharing in React. #ReactJS #HOC #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic

To view or add a comment, sign in

Explore content categories