𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗛𝗶𝗴𝗵𝗲𝗿 𝗢𝗿𝗱𝗲𝗿 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 (𝗛𝗢𝗖) 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁 Ever wondered how to reuse logic and structure across multiple components without repeating code? That’s where Higher Order Components (HOC) come in. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗮 𝗛𝗶𝗴𝗵𝗲𝗿 𝗢𝗿𝗱𝗲𝗿 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁? A Higher Order Component is a function that takes a component as input and returns a new enhanced component with additional functionality. In simple words: 𝘏𝘖𝘊 = 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯(𝘊𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵) → 𝘌𝘯𝘩𝘢𝘯𝘤𝘦𝘥𝘊𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵 𝗪𝗵𝘆 𝗱𝗼 𝘄𝗲 𝘂𝘀𝗲 𝗛𝗢𝗖𝘀? To follow the 𝗗𝗥𝗬 principle — “Don’t Repeat Yourself”. When multiple components need the same logic or structure, instead of duplicating code, we can wrap them with an HOC and reuse the behavior cleanly. 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 𝗼𝗳 𝘂𝘀𝗶𝗻𝗴 𝗛𝗢𝗖𝘀 • Code reusability • Cleaner and more modular code • Better separation of concerns • Consistent behavior across components • Industry-standard pattern used in large React codebases 𝗥𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝗲𝘅𝗮𝗺𝗽𝗹𝗲 In one of my applications, Navbar, Sidebar, and Footer were required on almost every page. Instead of manually adding these components to every page: I created a Layout HOC that includes Navbar, Sidebar, and Footer Then I passed each screen/page component into that HOC So the result became: (𝘓𝘢𝘺𝘰𝘶𝘵 𝘏𝘖𝘊 + 𝘗𝘢𝙜𝘦 𝘊𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵) → 𝘕𝘢𝘷𝘣𝘢𝘳 + 𝘚𝘪𝘥𝘦𝘣𝘢𝘳 + 𝘍𝘰𝘰𝘵𝘦𝘳 + 𝘗𝘢𝙜𝘦 𝘊𝘰𝘯𝘵𝘦𝘯𝘵 This made the codebase cleaner, easier to maintain, and scalable. 𝗪𝗵𝗲𝗻 𝘁𝗼 𝘂𝘀𝗲 𝗛𝗢𝗖𝘀? • When multiple components share the same logic. • When you want to add cross-cutting features like authentication, layouts, logging, or permissions. • When you want reusable and maintainable React architecture. Note: In modern React, hooks and layout components are often preferred, but HOCs are still widely used and important to understand — especially in real-world and legacy projects. Would love to hear your thoughts or real-world use cases of HOCs #React #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS
Understanding Higher Order Components (HOC) in React
More Relevant Posts
-
𝐘𝐨𝐮𝐫 `𝐮𝐬𝐞𝐌𝐞𝐦𝐨` 𝐢𝐬𝐧'𝐭 𝐚𝐥𝐰𝐚𝐲𝐬 𝐝𝐨𝐢𝐧𝐠 𝐰𝐡𝐚𝐭 𝐲𝐨𝐮 𝐭𝐡𝐢𝐧𝐤 𝐢𝐭 𝐢𝐬, 𝐞𝐬𝐩𝐞𝐜𝐢𝐚𝐥𝐥𝐲 𝐰𝐢𝐭𝐡 𝐨𝐛𝐣𝐞𝐜𝐭𝐬. I've seen so many teams struggle with React performance, reaching for `useMemo` like it's a silver bullet. But if you're memoizing a component, and its props include an object or array created inline, you might still be triggering unnecessary re-renders. Why? JavaScript's reference equality. ```javascript // The common pitfall: const MyComponent = React.memo(({ config }) => { /* ... */ }); function Parent() { // `configObject` is a new object on every render const configObject = { theme: 'dark', size: 'medium' }; return <MyComponent config={configObject} />; } ``` Even if `theme` and `size` values are the same, `configObject` is a new reference each time `Parent` renders. `React.memo` sees a new prop and re-renders `MyComponent`. The fix? Memoize the object itself: ```javascript const MyComponent = React.memo(({ config }) => { /* ... */ }); function Parent() { const configObject = useMemo(() => ({ theme: 'dark', size: 'medium' }), []); // Empty dependency array means it's created once return <MyComponent config={configObject} />; } ``` Now, `configObject` maintains its reference across `Parent` renders, letting `React.memo` on `MyComponent` actually do its job. This small detail can make a massive difference in complex applications with deeply nested or frequently updating components. It's not about premature optimization, it's about understanding how React and JavaScript work together. What's a subtle React performance trap you've encountered and fixed? #React #Frontend #JavaScript #WebDevelopment #Performance
To view or add a comment, sign in
-
Stop treating the JavaScript Event Loop like "Async Magic." Most of us use async/await, Promises, and setTimeout daily. Yet, we still encounter "mysterious" UI freezes and wonder why our code isn’t behaving as expected. The hard truth? Async code does NOT mean non-blocking UI. The browser doesn’t run your async code in parallel; it’s a single-threaded orchestrator scheduling work in a specific order. If you don't understand this order, you're likely writing bugs you can't see. The Hierarchy of Operations: 1. Call Stack: Your synchronous code always goes first. 2. Microtasks: Promises and async/await move to the front of the line. 3. Rendering: The browser attempts to update the UI. 4. Macrotasks: setTimeout and DOM events wait for all other tasks to finish. Three Common Misconceptions that Kill Performance: - "Async code is non-blocking." Wrapping a heavy for-loop in an async function doesn't make it faster; it still runs on the main thread. Heavy tasks will freeze the UI. - "setTimeout(fn, 0) is immediate." It’s not. It’s a way of saying, "I’ll wait until the stack is clear AND the browser has had a chance to render." It yields control, not speed. - "Promises are always safe." Microtasks (Promises) can "starve" the rendering process. The event loop processes the entire microtask queue before moving to rendering, which can lock your UI indefinitely. The Bottom Line: Frameworks like React, Angular, and Vue are not magic; they efficiently manage these queues. If your animations are lagging or your clicks feel unresponsive, examine your execution order rather than just your logic. The Golden Rule: Good frontend engineers write code that works. Great ones understand when the browser is allowed to breathe. #JavaScript #WebDevelopment #Frontend #WebPerformance #SoftwareEngineering #CodingTips
To view or add a comment, sign in
-
-
React Hooks didn’t just change syntax — they changed how we design UI systems. ⚙️🧠 Before hooks, stateful logic lived in class components, and “reuse” often meant HOCs, render props, and tangled lifecycles. Hooks made component logic composable again: small pieces of behavior you can share, test, and reason about. Why they matter in real projects 👇 ✅ Clearer mental model: state + effects are explicit. No hidden lifecycle edge cases. ✅ Reuse without wrappers: custom hooks turn messy cross-cutting concerns (auth, caching, analytics, feature flags) into clean APIs. ✅ Better performance control: useMemo/useCallback aren’t “speed buttons” — they’re tools to stabilize references for expensive computations and child renders. ✅ Fits modern frameworks: Next.js + React Server Components push more work to the server, but hooks still define predictable client boundaries (“use client”) and interactive behavior. Practical takeaway: treat useEffect as integration glue, not a default. If derived state can be computed during render, don’t store it. If an effect exists, ask: “what external system am I syncing with?” 🔌 What’s the hook pattern you rely on most in production? 👀 #react #javascript #nextjs #frontend #webdev #softwareengineering
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗥𝗲𝗮𝗰𝘁 𝗛𝗼𝗼𝗸 𝗧𝗵𝗮𝘁 𝗖𝗼𝗻𝗳𝘂𝘀𝗲𝘀 𝗘𝘃𝗲𝗿𝘆𝗼𝗻𝗲 𝗕𝘂𝘁 𝗜𝘀 𝗔𝗯𝘀𝗼𝗹𝘂𝘁𝗲𝗹𝘆 𝗘𝘀𝘀𝗲𝗻𝘁𝗶𝗮𝗹 Every React developer eventually encounters useEffect. It's designed for "side effects" in functional components. Things like data fetching, subscriptions, or manually changing the DOM. 🎯 WHAT IS IT? useEffect allows you to perform side effects after your component renders. It essentially gives functional components the capabilities of lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. 🤔 WHY IS IT TRICKY? Many developers struggle with its second argument: the dependencies array. Forgetting it or misconfiguring it leads to bugs like infinite loops or stale closures. ✅ THE SECRET SAUCE: DEPENDENCIES ARRAY This array tells React when to re-run your effect. An empty array [] means the effect runs once after the initial render and cleans up on unmount. Omitting the array means the effect runs after every render. This is rarely what you want. Including variables means the effect runs whenever those variables change. 🧹 CLEANUP IS CRITICAL Sometimes, your effect needs to clean up after itself. Think about removing event listeners or canceling network requests. You do this by returning a function from your useEffect callback. This returned function runs when the component unmounts, or before the effect re-runs due to dependency changes. Mastering useEffect is a game-changer for building robust React applications. It simplifies complex asynchronous logic and resource management. If you found this helpful, like and share it with your network! #React #JavaScript #FrontendDevelopment #WebDevelopment #ReactHooks
To view or add a comment, sign in
-
-
⚛️React Journey: Custom Hooks Custom Hooks solve React's biggest pain: duplicating useEffect + useState logic across components. Extract reusable logic into useSomething() functions to make your code DRY, testable, and clean. Why Custom Hooks? Reusable Logic: Share data-fetching, window resize, or localStorage logic. Component Focus: Components become pure UI (no business logic). Easy Testing: Test the hook in isolation. Rules: Must start with "use", call hooks only at top level. Custom Hooks make React feel like writing vanilla JS functions with superpowers. What's your favourite Custom Hook to use or build? #React #CustomHooks #ReactHooks #JavaScript #CleanCode #DeveloperLife #WebDevelopment #Frontend #Backend #FullStack #WebDevHumor #CodingLife #ProgrammerHumor #JavaScript #ReactJS #CSS #HTML #NodeJS #TechLife #DeveloperLife #SoftwareEngineering #Productivity #TechCommunity #LinkedInCreators #EngineeringCulture #Entri
To view or add a comment, sign in
-
🧠 The JavaScript Event Loop — the reason your “async” code behaves weirdly Ever seen this and felt betrayed? setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); You expected: timeout promise But JavaScript said: promise timeout This is the moment where most developers either memorize rules or actually understand JavaScript. Let’s talk about what’s really happening. JavaScript is single-threaded. There is one Call Stack. One thing runs at a time. So how does JS handle timers, network calls, UI events, and still feel async? It cheats. Very intelligently. Call Stack This is where synchronous code runs. Functions execute one by one. If something blocks here, everything waits. APIs (Browser / Node) Async work is pushed outside the stack. Timers, fetch, file reads happen here. Once finished, callbacks don’t jump back immediately. They wait. Queues (this part matters) Microtask Queue Promises (then, catch, finally) queueMicrotask Highest priority. Always drained first. Macrotask Queue setTimeout setInterval UI events Event Loop (the scheduler) It keeps checking: Is the call stack empty? Run all microtasks Run one macrotask Allow render Repeat forever That’s why promises beat timers every time. The hidden trap Microtask starvation. Too many chained promises can delay rendering, make timers feel broken, and freeze the UI without obvious loops. Why this matters in real projects React state batching Unexpected re-renders Next.js streaming behavior Node.js performance issues Race conditions that disappear when you add console.log If you don’t understand the Event Loop,you debug symptoms. If you do,you debug causes. #JavaScript #EventLoop #AsyncJS #ReactJS #NextJS #FrontendEngineering #WebPerformance
To view or add a comment, sign in
-
Topic: React Performance Optimization – What Actually Matters ⚡ React Performance Optimization – What Actually Matters Before adding useMemo, useCallback, or fancy libraries… ask yourself one question: Is there really a performance problem? Here’s what actually makes the biggest impact 👇 🔹 Split Components Properly Smaller components = fewer re-renders. 🔹 Avoid Unnecessary State Less state → less complexity → better performance. 🔹 Use Keys Correctly in Lists Wrong keys cause UI bugs + wasted re-renders. 🔹 Understand Re-renders Re-render ≠ DOM update (React is already optimized). 🔹 Measure Before Optimizing Use React DevTools Profiler, not guesswork. 💡 Hard Truth Most performance issues come from bad architecture, not missing hooks. 📌 Golden Rule Optimize when needed, not by default. 📸 Daily React tips & visuals: 👉 https://lnkd.in/g7QgUPWX 💬 What was the real cause of your last performance issue? 👍 Like | 🔁 Repost | 💭 Comment #React #ReactPerformance #FrontendDevelopment #JavaScript #WebDevelopment #ReactJS #DeveloperLife
To view or add a comment, sign in
-
⚛️ React.js – useState Hook The useState Hook allows functional components to store and manage state. It is one of the most commonly used hooks in React and plays a key role in building interactive user interfaces. ✔ useState Syntax useState is a function provided by React that returns two values: The current state value A function to update that state The initial state can be a number, string, boolean, array, or object. This simple syntax replaces complex state logic previously handled by class components. ✔ Updating State State updates are done using the state updater function. Important points: State should never be updated directly Using the updater function ensures React tracks changes correctly Updates can be based on previous state values When state updates, React schedules a UI update automatically. ✔ Multiple States A component can have multiple state variables. Why this matters: Keeps related data separate Improves readability Makes logic easier to manage Instead of storing everything in one state object, React encourages using multiple useState calls. ✔ Re-rendering Concept Whenever state changes: React re-renders the component Only the affected parts of the UI are updated Virtual DOM ensures efficient rendering Re-rendering is how React keeps the UI in sync with the latest state. ✔ Why useState Is Important Enables interactivity Simplifies state management Makes functional components powerful Encourages clean and readable code The useState hook is the foundation for handling user-driven changes in React. 🔑 Key Takeaway State changes → React re-renders → UI updates automatically. #ReactJS #useState #Hooks #FrontendDevelopment #WebDevelopment #LearningInPublic #JavaScript
To view or add a comment, sign in
-
-
🚀 Day 8 Not Just Motivation — Real Concepts to Build Strong Technical Understanding (Part 8) Why does JavaScript remember variables even after a function finishes? The answer is Closure. Let’s understand this using a real-world example from React: useState. A simplified mental model of useState (conceptual) function useState(initialValue) { let state = initialValue; function setState(newValue) { state = newValue; render(); // re-render component } return [state, setState]; } Here, setState is a closure. It remembers state even after useState finishes execution. Example: Counter Component function Counter() { const [count, setCount] = React.useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } Every render is a new function call. So how does React remember count? Let’s go step by step. Render 1 – Initial Mount 1. React calls the component: Counter(). 2. useState(0) runs and creates a state slot outside the function (heap/fiber). 3. count is set to 0 and setCount is returned as a closure. 4. JSX is rendered and UI shows Count: 0. User Clicks the Button 1. Browser triggers a click event. 2. React handles the event via its synthetic event system. 3. setCount(count + 1) is called. 4. React updates internal state and schedules a re-render. Render 2 – After State Update 1. Counter() runs again. 2. Local variables are recreated, but state is preserved. 3. useState does not reinitialize; it reads existing state from memory. 4. count is now 1 and UI updates accordingly. Final Takeaway The component function re-runs on every render, but state survives because React stores it outside the function. setState works because it is a closure pointing to that preserved state. Closures are the reason useState works. #javascript #closure #reactjs #reacthooks #frontend #webdevelopment
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Sanjana Sharma Good summary, but: 1) would be great to mention the downsides of using HOCs in large and complex codebases (that's why we moved away from them to hooks) 2) IMO your real-world example should describe extending component behaviour, that's the main point of HOCs (creating a new component just because we want to wrap it with some page structure? seems like more trouble down the line, especially since we already have solutions for that - children, render props, outlets, etc.)