Higher Order Components (HOC) in React: Complete Guide with Examples

When working with React, you’ll often need to reuse logic across multiple components.

That’s where Higher Order Components (HOC) come into the picture.

In this guide, you’ll learn:

  • What a Higher Order Component is
  • Why we need it
  • How it works
  • Multiple real-world examples
  • When to use and when to avoid

What is a Higher Order Component (HOC)?

Simple Definition

A Higher Order Component (HOC) is a function that takes a component and returns a new enhanced component.


Syntax

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Simple Example

function withLogger(Component) {
return function EnhancedComponent(props) {
console.log("Component rendered");
return <Component {...props} />;
};
}

👉 Usage:

function Button() {
return <button>Click</button>;
}

const EnhancedButton = withLogger(Button);

Why Do We Need HOC?

Without HOC:

❌ Duplicate logic in multiple components

With HOC:

✅ Reuse logic
✅ Cleaner code
✅ Better maintainability


How HOC Works (Step-by-Step)

  1. Take a component as input
  2. Add extra logic
  3. Return a new component
  4. Render original component with props

Scenario 1: Logging (Basic Example)

function withLogger(Component) {
return function (props) {
console.log("Props:", props);
return <Component {...props} />;
};
}

Scenario 2: Authentication (Very Common)

HOC

function withAuth(Component) {
return function (props) {

const { isLoggedIn } = useContext(AuthContext);

if (!isLoggedIn) {
return <h2>Please Login</h2>;
}

return <Component {...props} />;
};
}

Usage

function Dashboard() {
return <h1>Welcome to Dashboard</h1>;
}

export default withAuth(Dashboard);

Scenario 3: API Data Fetching


HOC

import { useEffect, useState } from "react";

function withData(Component, url) {
return function (props) {
const [data, setData] = useState([]);

useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData);
}, []);

return <Component data={data} {...props} />;

};
}

Usage

function Users({ data }) {
return <div>{data.length} Users</div>;
}

export default withData(Users, "/api/users");

Scenario 4: Loading State

function withLoading(Component) {
return function ({ isLoading, ...props }) {
if (isLoading) return <p>Loading...</p>;
return <Component {...props} />;
};
}

Scenario 5: Reusing Styles

function withStyle(Component) {
return function (props) {
return (
<div style={{ border: "1px solid black", padding: "10px" }}>
<Component {...props} />
</div>
);
};
}

Common Mistakes


❌ Forgetting to pass props

return <Component />; // ❌

👉 Fix:

return <Component {...props} />; // ✅

❌ Mutating original component

👉 Always return a new component


HOC vs Hooks


HOC

  • Works with class components
  • Reusable logic

Hooks

  • Simpler
  • Preferred in modern React

When to Use HOC

Use HOC when:

  • You need reusable logic
  • Working with legacy/class components
  • Cross-cutting concerns (auth, logging)

When to Avoid HOC

Avoid when:

  • Hooks can solve it easily
  • Too many nested HOCs (complexity increases)

🧠 Interview Tip

If asked:

“What is HOC?”

👉 Answer:

“A Higher Order Component is a function that takes a component and returns a new component with added functionality.”


🏁 Final Summary

  • HOC = function that enhances components
  • Helps reuse logic
  • Used for auth, logging, data fetching
  • Hooks are modern alternative

🔗 Related Articles

👉 Add these:


💡 Found this helpful? Subscribe for simple React guides, real-world examples, and interview preparation tips. Happy Coding!

What is DOM, Virtual DOM, and Real DOM in React? (Simple Explanation for Beginners)

If you are new to web development or React, you might have heard terms like:

  • DOM
  • Virtual DOM
  • Real DOM

And it can feel confusing 😅

Don’t worry — in this guide, we’ll explain everything in very simple terms, even if you are not from a technical background.


What is DOM?

DOM stands for:

Document Object Model

👉 In simple words:

DOM is a structure of your web page


Real-Life Analogy

Think of a web page like a house 🏠

  • Walls → HTML elements
  • Furniture → Content
  • Layout → Structure

👉 DOM is like the blueprint of the house


Example

<h1>Hello</h1>
<p>Welcome to my website</p>

👉 Browser converts this into a structure like:

Page
├── h1 → "Hello"
└── p → "Welcome to my website"

What is Real DOM?

Real DOM is:

The actual DOM in the browser


Problem with Real DOM

Whenever something changes:

👉 The browser may rebuild or update large parts of the page

This can be:

  • Slow
  • Inefficient
  • Costly for performance

Example

Imagine:

👉 You change one word on the page

❌ Browser may re-check or update entire section


What is Virtual DOM?

Virtual DOM is a concept used by React


Simple Definition

Virtual DOM is a lightweight copy of the Real DOM


Real-Life Analogy

Think like this:

👉 Instead of directly editing your house 🏠
👉 You first make changes in a model (mini version)

Then:

✔ Compare changes
✔ Update only what is needed


How Virtual DOM Works (Step-by-Step)


Step 1: Initial Render

React creates:
👉 Virtual DOM
👉 Real DOM


Step 2: State Changes

When something changes:

👉 React creates a new Virtual DOM


Step 3: Comparison (Diffing)

React compares:

  • Old Virtual DOM
  • New Virtual DOM

Step 4: Update Only Changes

👉 React updates only the changed parts in Real DOM


Example (Very Simple)


Initial UI

<h1>Hello</h1>

Updated UI

<h1>Hello World</h1>

What React Does

❌ Does NOT reload whole page
✅ Updates only text inside <h1>


Why Virtual DOM is Faster

FeatureReal DOMVirtual DOM
UpdatesFull or largeOnly required parts
SpeedSlowerFaster
EfficiencyLowHigh

Key Differences (Simple Table)

FeatureReal DOMVirtual DOM
TypeActual UICopy of UI
SpeedSlowFast
UpdatesDirectIndirect
Used byBrowserReact

Why React Uses Virtual DOM

React uses Virtual DOM to:

✔ Improve performance
✔ Reduce unnecessary updates
✔ Make apps faster


Real-World Example

Imagine a shopping app:

👉 You add 1 item

❌ Without Virtual DOM → entire page refresh
✅ With Virtual DOM → only cart updates


Common Misunderstanding


❌ Virtual DOM replaces Real DOM

👉 Not true

👉 It works along with Real DOM


Interview Tip

If asked:

“What is Virtual DOM?”

👉 Answer:

“It is a lightweight copy of the Real DOM used by React to efficiently update only changed parts of the UI.”


Final Summary

  • DOM = structure of webpage
  • Real DOM = actual browser DOM
  • Virtual DOM = lightweight copy used by React
  • React updates only changed parts → faster performance

💡 Found this helpful? Subscribe to get simple explanations of complex concepts, React tutorials, and coding tips. Happy Coding!

What is React JS? Why is it Efficient? (Beginner-Friendly Guide)

If you are starting frontend development, one of the most popular technologies you’ll hear about is React JS.

But many beginners ask:

🤔 What exactly is React?
🤔 Why do companies prefer React over other frameworks?

In this guide, you’ll learn:

  • What React JS is
  • How it works
  • Why it is efficient
  • Real-world examples

What is React JS?

React is a JavaScript library used to build user interfaces (UI), especially for web applications.

👉 It was developed by Meta (formerly Facebook).


Simple Definition

React is a library that helps you build fast, interactive, and reusable UI components.


Example of React Code

function App() {
return <h1>Hello, World!</h1>;
}

👉 This renders a heading on the screen.


How React Works

React uses a component-based architecture.


What are Components?

Components are small reusable pieces of UI.

Example:

  • Header
  • Footer
  • Button
  • Form

Example

function Button() {
return <button>Click Me</button>;
}

👉 You can reuse this anywhere in your app.


Why is React Efficient?

This is the most important question 👇


1. Virtual DOM (Main Reason)

React uses something called the Virtual DOM.


What is DOM?

DOM = Document Object Model
👉 Represents your webpage structure


Problem with Normal DOM

  • Slow updates
  • Entire UI re-renders

React Solution: Virtual DOM

React creates a lightweight copy of the DOM.

👉 When data changes:

  • React compares old vs new (diffing)
  • Updates only changed parts

Result:

✔ Faster updates
✔ Better performance


2. Reusable Components

Instead of writing code again and again:

<Button />
<Button />
<Button />

👉 One component → multiple uses


3. Efficient Rendering

React updates only what is needed:

❌ Not entire page
✅ Only changed components


4. One-Way Data Flow

React uses unidirectional data flow:

👉 Parent → Child

Benefits:

  • Easy debugging
  • Predictable behavior

5. Declarative Approach

Instead of telling “how to update UI”:

👉 You describe “what UI should look like”

Example:

const isLoggedIn = true;return isLoggedIn ? <Dashboard /> : <Login />;

6. Strong Ecosystem

React has:

  • Huge community
  • Many libraries
  • Easy integrations

Real-World Example

Imagine a shopping app:

👉 When you add an item:

  • Only cart updates
  • Not entire page

👉 This is React efficiency 🚀


React vs Traditional Approach

FeatureTraditional JSReact
UpdatesFull pagePartial
Code reuseLowHigh
PerformanceSlowerFaster

Common Misconceptions


❌ React is a Framework

👉 It’s actually a library


❌ React is only for big apps

👉 You can use it for small apps too


When to Use React?

Use React when:

  • Building dynamic UI
  • Creating large applications
  • Need reusable components

Interview Tip

If asked:

“Why is React efficient?”

👉 Answer:

“Because it uses Virtual DOM, updates only required parts, and uses reusable components.”


Final Summary

  • React is a UI library
  • Uses components
  • Virtual DOM improves performance
  • Efficient rendering saves time

👉 That’s why React is widely used 🚀

💡 Found this helpful? Subscribe to get simple React tutorials, interview questions, and real-world examples. Happy Coding!

Showing Alert For Page Refresh , Closing tab or Window If Unsaved changes are there in the Form – ReactJS

If unsaved changes are there in the form, we will use the following code to show default alert message when user tries to reload or close the window or close the tab.

How to find outdated packages/libraries in the project – ReactJS ?

To find outdated packages / libraries in a project we need to run the following command if we are using npm + package-lock.json

If our project uses yarn + yarn.lock, then we need to run the following command to find outdated packages / libraries in a project.