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
Shiv Upadhyay’s Post
More Relevant Posts
-
𝐀𝐝𝐯𝐚𝐧𝐜𝐞𝐝 𝐑𝐞𝐚𝐜𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🚀 Many developers use "key" in React… but don’t fully understand why it’s important. Question: Why should we NOT use index as key in React lists? 🤔 Example 👇 const items = ["A", "B", "C"]; items.map((item, index) => ( Looks fine… right? ❌ Now imagine removing "A" from the list 👇 ["B", "C"] React will reuse DOM elements incorrectly because index changes. Result? ⚠️ Wrong UI updates ⚠️ State mismatch ⚠️ Unexpected bugs Correct way ✅ items.map((item) => ( Why? React uses "key" to track elements during reconciliation (Virtual DOM diffing). If keys are unstable (like index), React cannot correctly identify elements. Tip for Interview ⚠️ Key should be: ✔ Unique ✔ Stable ✔ Predictable Good developers write lists. Great developers understand reconciliation. #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #ReactInterview #AdvancedReact #CodingInterview #SoftwareDeveloper
To view or add a comment, sign in
-
-
🔥 Stale Closure in React — A Common Bug You Must Know Ever faced a situation where your state is not updating correctly inside setTimeout / setInterval / useEffect? 🤯 👉 That’s called a Stale Closure --- 💡 What is happening? A function captures the old value of state and keeps using it even after updates. --- ❌ Example (Buggy Code): import { useState, useEffect } from "react"; function Counter() { const [count, setCount] = useState(0); useEffect(() => { setInterval(() => { console.log(count); // ❌ Always logs 0 (stale value) }, 1000); }, []); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } 👉 Why? Because the closure captured "count = 0" when the effect first ran. --- ✅ Fix (Correct Approach): useEffect(() => { const id = setInterval(() => { setCount(prev => prev + 1); // ✅ always latest value }, 1000); return () => clearInterval(id); }, []); --- 🎯 Key Takeaway: Closures + async code (setTimeout, setInterval, event listeners) = ⚠️ potential stale state bugs --- 💬 Interview One-liner: “Stale closure happens when a function uses outdated state due to how closures capture variables.” --- 🚀 Mastering this concept = fewer bugs + stronger React fundamentals #ReactJS #JavaScript #Frontend #InterviewPrep #Closures #WebDevelopment
To view or add a comment, sign in
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers understand closures in JavaScript… but get confused when it comes to React. Question: What will be the output of this code? Example 👇 import React, { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { console.log(count); }, 1000); }; return ( <> Click </> ); } Now imagine: You click the button 3 times quickly and count updates each time What will be logged after 1 second? Answer 👇 It will log the SAME value multiple times ❌ Why? Because of closure. The setTimeout callback captures the value of count at the time handleClick was created. This is called a “stale closure”. Correct approach ✅ setTimeout(() => { setCount(prev => { console.log(prev); return prev; }); }, 1000); Or use useRef for latest value. Tip for Interview ⚠️ Closures + async code can lead to stale state bugs in React. Good developers know closures. Great developers know how closures behave in React. #ReactJS #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks
To view or add a comment, sign in
-
🚀 Closure in JavaScript — Explained Like a Senior React Developer Closures are one of those concepts that look simple… but power some of the most critical patterns in React ⚡ 👉 What is a Closure? A closure is when a function remembers variables from its outer scope, even after the outer function has finished execution. 💡 In short: Function + Lexical Scope = Closure --- 🔹 Basic Example function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 👉 Even though outer() is done, inner() still remembers count That’s the power of closure. --- 🔹 Why Closures Matter in React? Closures are everywhere in React: ✔️ Hooks (useState, useEffect) ✔️ Event handlers ✔️ Async operations (setTimeout, API calls) ✔️ Custom hooks --- 🔹 Real-world React Problem: Stale Closure ⚠️ setCount(count + 1); setCount(count + 1); ❌ Both use the same old value of count ✅ Correct approach: setCount(prev => prev + 1); setCount(prev => prev + 1); 👉 This avoids stale closure and ensures latest state is used --- 🔹 Where Closures Help ✅ Data encapsulation (private variables) ✅ Memoization & performance optimization ✅ Debouncing / throttling ✅ Custom hooks ✅ Cleaner state management --- 🔥 Pro Insight (Senior Level) Closures are the backbone of React’s functional paradigm. Misunderstanding them can lead to bugs in: useEffect dependencies Async logic Event callbacks --- 💬 One-line takeaway 👉 “Closures allow functions to retain access to their scope — making React hooks and async logic work seamlessly.” --- #JavaScript #ReactJS #Frontend #WebDevelopment #Programming #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
Building a Scalable React Architecture: Clean Code & High Performance 🚀 I’m excited to share a quick walkthrough of my latest React project! 💻 My main focus was on creating a Senior-level architecture that is both clean and highly optimized. Key Technical Highlights: ✅ Logic Separation: Used Custom Hooks to keep UI components clean and focused. ✅ Performance: Implemented useMemo to prevent unnecessary re-renders. ✅ State Management: Efficiently handled global state using the Context API. I love building applications that aren't just functional, but also scalable and maintainable 🔗 Explore the code on GitHub: https://lnkd.in/eYEfnt-J #ReactJS #WebDevelopment #FrontendEngineer #CleanCode #ContextAPI #PerformanceOptimization #JavaScript #SoftwareEngineering #HappyCoding #Memorization
To view or add a comment, sign in
-
🚀 Controlled vs Uncontrolled Components in React — Real-World Perspective Most developers learn: 👉 Controlled = React state 👉 Uncontrolled = DOM refs But in real applications… 👉 The choice impacts performance, scalability, and maintainability. 💡 Quick Recap 🔹 Controlled Components: Managed by React state Re-render on every input change 🔹 Uncontrolled Components: Managed by the DOM Accessed via refs ⚙️ The Real Problem In large forms: ❌ Controlled inputs → Too many re-renders ❌ Uncontrolled inputs → Hard to validate & manage 👉 So which one should you use? 🧠 Real-world Decision Rule 👉 Use Controlled when: ✔ You need validation ✔ UI depends on input ✔ Dynamic form logic exists 👉 Use Uncontrolled when: ✔ Performance is critical ✔ Minimal validation needed ✔ Simple forms 🔥 Performance Insight Controlled input: <input value={name} onChange={(e) => setName(e.target.value)} /> 👉 Re-renders on every keystroke Uncontrolled input: <input ref={inputRef} /> 👉 No re-render → better performance ⚠️ Advanced Problem (Most devs miss this) 👉 Large forms with 20+ fields Controlled approach: ❌ Can slow down typing 👉 Solution: ✔ Hybrid approach ✔ Use libraries (React Hook Form) 🧩 Industry Pattern Modern apps often use: 👉 Controlled logic + Uncontrolled inputs internally Example: ✔ React Hook Form ✔ Formik (optimized patterns) 🔥 Best Practices ✅ Use controlled for logic-heavy forms ✅ Use uncontrolled for performance-critical inputs ✅ Consider form libraries for scalability ❌ Don’t blindly use controlled everywhere 💬 Pro Insight (Senior Thinking) 👉 This is not about “which is better” 👉 It’s about choosing the right tool for the problem 📌 Save this post & follow for more deep frontend insights! 📅 Day 17/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #PerformanceOptimization #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🎯 React useMemo vs useCallback — Stop Guessing, Start Using Them Right One of the most commonly asked React interview questions… yet one of the most misunderstood in real-world projects. Let’s break it down professionally and practically 👇 💡 useMemo — Memoize Values Use useMemo when you want to cache the result of an expensive calculation. 🔹 Prevents unnecessary recomputation 🔹 Returns a memoized value 🔹 Runs only when dependencies change 👉 Example use case: Filtering a large list or computing derived data ⚙️ useCallback — Memoize Functions Use useCallback when you want to cache a function reference. 🔹 Prevents unnecessary function re-creation 🔹 Useful when passing callbacks to child components 🔹 Helps avoid unwanted re-renders (especially with React.memo) 👉 Example use case: Event handlers passed to optimized child components 🚀 Key Difference ✔ useMemo → returns a value ✔ useCallback → returns a function ⚠️ Important Reality Check Using these hooks everywhere can actually hurt performance. 👉 They add overhead 👉 They should be used only when there’s a real performance issue 🔥 When to Use Them (Practical Rule) ✔ Use useMemo → when computation is expensive ✔ Use useCallback → when function identity matters Otherwise… keep your code simple. 💼 Interview Insight Don’t just define them. Explain when NOT to use them — that’s what shows real understanding. 💬 Have you ever optimized a React app using these hooks? Did it actually improve performance? #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #SoftwareEngineering #CodingInterview #TechCareers
To view or add a comment, sign in
-
-
🚀 Why useState is a Game-Changer in React. let's breakdown this 👇 💡 What is useState? "useState" is a React Hook that allows you to store and manage dynamic data (state) inside functional components. Without it, your UI wouldn’t respond to user input. 📱 Real-Time Example: Form Input & Validation Let’s take a simple login form 👇 import React, { useState } from "react"; function LoginForm() { const [email, setEmail] = useState(""); const [error, setError] = useState(""); const handleSubmit = (e) => { e.preventDefault(); if (!email.includes("@")) { setError("Please enter a valid email address"); } else { setError(""); alert("Form submitted successfully!"); } }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)} /> {error && <p style={{ color: "red" }}>{error}</p>} <button type="submit">Submit</button> </form> ); } export default LoginForm 🧠 What’s happening here? - "email" → stores user input - "setEmail" → updates input as the user types - "error" → stores validation message - "setError" → shows/hides error instantly useState is what connects user actions to UI behavior. It ensures your forms are not just functional, but smart and responsible 💬 Have you implemented form validation using useState? What challenges did you face? #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
🚀React Issue I Faced While Optimizing Performance… My component was re-rendering unnecessarily, causing performance issues in my app 😓 After debugging, I identified the root cause 👇 🔴 Problem: Unnecessary re-renders affecting performance 🟠 Mistake: Functions and values were being recreated on every render → No memoization used 🟢 Solution: Used useCallback and useMemo to optimize performance Example: const memoizedFn = useCallback(() => { // function logic }, []); const computedValue = useMemo(() => { return expensiveCalculation(data); }, [data]); 💡 Key Insight: React re-renders can impact performance if not optimized properly. Memoization helps in controlling unnecessary updates. 👉 Optimization is not optional in scalable applications It helps recruiters notice your practical knowledge and experience. How do you handle performance optimization in React? 👇 #ReactJS #FrontendDevelopment #PerformanceOptimization #JavaScript #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