React SVG Import: What Does “ReactComponent as” Mean?

If you’ve worked with React, you might have seen this syntax:

import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';

And wondered:

πŸ€” What is ReactComponent?
πŸ€” How is an SVG becoming a React component?
πŸ€” When should we use this?

Let’s break it down step-by-step in a very simple way πŸ‘‡


What Does This Syntax Mean?

import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';

πŸ‘‰ This means:

β€œImport the SVG file and use it as a React component”


Usage

<SomeIcon />

πŸ‘‰ Instead of:

<img src="some-icon.svg" />

How Does This Actually Work?

This is not plain JavaScript behavior.

πŸ‘‰ It is handled by your build tool (like Webpack or Vite).


Behind the Scenes

Tools like:

  • SVGR (SVG to React transformer)

convert your SVG file into:

function SomeIcon(props) {
return (
<svg {...props}>
{/* SVG content */}
</svg>
);
}

πŸ‘‰ So your SVG becomes a React component internally


Normal SVG vs React Component

❌ Traditional Way

<img src="/icon.svg" alt="icon" />

βœ… React Component Way

import { ReactComponent as Icon } from './icon.svg';

<Icon />

Why Use SVG as React Component?


1. Easy Styling

<Icon style={{ color: 'red', width: 50 }} />

πŸ‘‰ You can style it like a component


2. Dynamic Props

<Icon width={30} height={30} />

3. Better Control

You can:

  • Change color
  • Animate
  • Add events

Add Event Handlers

<Icon onClick={() => alert('Clicked')} />

Example (Real Usage)

SVG File

<!-- icon.svg -->
<svg viewBox="0 0 24 24">
<path d="..." />
</svg>

React Usage

import { ReactComponent as Icon } from './icon.svg';

function App() {
return <Icon width={40} height={40} />;
}

Styling with CSS

.icon {
fill: blue;
}
<Icon className="icon" />

Important Note (Color Control)

For dynamic color:

πŸ‘‰ SVG must use:

fill="currentColor"

πŸ‘‰ Then:

<Icon style={{ color: 'green' }} />

Common Mistakes

❌ Using wrong import

import Icon from './icon.svg'; // ❌

πŸ‘‰ This gives image path, not component


❌ Missing configuration

πŸ‘‰ Works only if:

  • CRA (Create React App)
  • Vite (with plugin)
  • Webpack configured

When It Works Automatically

Works out-of-the-box in:

  • Create React App
  • Vite (with SVGR plugin)
  • Next.js (with config)

When to Use <img> vs Component

Use <img> when:

  • Simple display
  • No styling needed

Use React Component when:

  • Need styling
  • Need animations
  • Need dynamic behavior

Interview Tip

If asked:

β€œWhat is ReactComponent as in SVG import?”

πŸ‘‰ Answer:

β€œIt converts SVG into a React component using tools like SVGR, allowing us to use it like JSX.”


Final Summary

  • ReactComponent converts SVG β†’ React component
  • Enables styling, events, and dynamic behavior
  • Powered by tools like SVGR
  • Better than <img> for interactive UI

Related Articles


πŸ’‘ Found this helpful? Subscribe for simple React tips, real-world examples, and developer-friendly tutorials. Happy Coding!

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!

Type vs Interface in TypeScript: Complete Guide with Examples (Beginner to Advanced)

When working with TypeScript, one of the most common questions is:

πŸ€” Should I use type or interface?

Both are used to define the structure of data, but they behave differently in certain scenarios.

In this guide, you’ll learn:

  • What type and interface are
  • Key differences
  • All important scenarios with examples
  • When to use each (very important)

What is interface in TypeScript?

An interface is used to define the structure (shape) of an object.


Basic Example

interface User {
name: string;
age: number;
}
const user: User = {
name: "Raju",
age: 25,
};

What is type in TypeScript?

A type is more flexible and can define:

  • Objects
  • Primitives
  • Unions
  • Tuples
  • Functions

Basic Example

type User = {
name: string;
age: number;
};

πŸ‘‰ Works similar to interface for objects


Key Differences (Quick Overview)

Featureinterfacetype
Object structureβœ… Yesβœ… Yes
Union types❌ Noβœ… Yes
Intersection types⚠️ Limitedβœ… Yes
Declaration mergingβœ… Yes❌ No
FlexibilityMediumHigh

Scenario 1: Object Definition

πŸ‘‰ Both work the same

interface User {
name: string;
}
type User = {
name: string;
};

βœ… No major difference here


Scenario 2: Declaration Merging (Important)

βœ… interface supports merging

interface User {
name: string;
}

interface User {
age: number;
}

πŸ‘‰ Result:

{
name: string;
age: number;
}

❌ type does NOT support merging

type User = {
name: string;
};

type User = {
age: number;
}; // ❌ Error

Scenario 3: Union Types

βœ… Using type

type Status = "success" | "error" | "loading";

❌ interface cannot do this

πŸ‘‰ Not supported


Scenario 4: Intersection Types

βœ… Using type

type Person = {
name: string;
};

type Employee = Person & {
salary: number;
};

⚠️ interface alternative

interface Person {
name: string;
}

interface Employee extends Person {
salary: number;
}

Scenario 5: Functions

βœ… Using type

type Add = (a: number, b: number) => number;

βœ… Using interface

interface Add {
(a: number, b: number): number;
}

Scenario 6: Extending / Inheritance

interface

interface Person {
name: string;
}

interface Employee extends Person {
salary: number;
}

type

type Person = {
name: string;
};

type Employee = Person & {
salary: number;
};

Scenario 7: Primitive Types

βœ… Only type supports this

type ID = string | number;

πŸ‘‰ interface cannot do this ❌


Scenario 8: Tuples

type Point = [number, number];

πŸ‘‰ Only type supports tuples


Scenario 9: Working with Classes

interface (preferred)

interface User {
name: string;
}

class Person implements User {
name = "Raju";
}

When to Use interface

Use interface when:

  • Defining object structure
  • Working with classes
  • Need declaration merging
  • Building large applications

When to Use type

Use type when:

  • Using unions (|)
  • Using intersections (&)
  • Working with primitives
  • Advanced type logic

Best Practice (Very Important)

πŸ‘‰ Use both together:

type Status = "success" | "error";

interface ApiResponse {
status: Status;
data: string;
}

Common Mistakes


❌ Using interface for unions

interface Status = "success" | "error"; // ❌

❌ Overusing any

πŸ‘‰ Avoid losing type safety


❌ Confusion between both

πŸ‘‰ Use based on use case


Interview Tip

If asked:

β€œtype vs interface?”

πŸ‘‰ Answer:

β€œBoth define data shapes, but type is more flexible (supports unions, tuples), while interface supports declaration merging and is better for object-oriented design.”


Final Summary

  • Both define structure of data
  • interface β†’ best for objects & classes
  • type β†’ best for advanced types
  • Use both based on need

πŸ’‘ Found this helpful? Subscribe to get simple TypeScript tutorials, interview questions, and real-world 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!

How to Find Sum of Array Using reduce() in JavaScript (Step-by-Step Execution Explained)

Finding the sum of array elements is one of the most common tasks in JavaScript.
While there are multiple ways to do it, the reduce() method is the most powerful and preferred approach.

In this post, you’ll learn:

  • What reduce() is ?
  • How to use it to find sum
  • Step-by-step execution (very important)
  • What happens if you don’t provide initial value
  • Common mistakes to avoid

Let’s get started πŸ‘‡


What is reduce() in JavaScript?

The reduce() method is used to:

Convert an array into a single value

This value can be:

  • Sum
  • Product
  • Object
  • String

Problem Statement

Write a JavaScript program to find the sum of array elements using reduce().


Basic Example

const numbers = [10, 20, 30, 40];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 100

Understanding the Syntax

array.reduce((acc, curr) => acc + curr, initialValue);

Parameters:

  • acc β†’ accumulator (stores result)
  • curr β†’ current element
  • initialValue β†’ starting value (important!)

Step-by-Step Execution (Very Important)

Let’s understand how this works internally.

Input:

[10, 20, 30, 40]

Code:

numbers.reduce((acc, curr) => acc + curr, 0);

Execution Flow Table

StepacccurrOperationResult
10100 + 1010
2102010 + 2030
3303030 + 3060
4604060 + 40100

Final Output

100

How reduce() Works Internally

You can think of reduce() like this:

let acc = 0;for (let i = 0; i < numbers.length; i++) {
acc = acc + numbers[i];
}

πŸ‘‰ It keeps updating the acc value until all elements are processed.


What Happens If You Don’t Provide Initial Value?

numbers.reduce((acc, curr) => acc + curr);

Execution Without Initial Value

StepacccurrResult
Start102030
Next303060
Next6040100

πŸ‘‰ Here:

  • acc starts as first element (10)
  • Loop starts from second element (20)

Problem with Empty Array

[].reduce((acc, curr) => acc + curr);

πŸ‘‰ πŸ’₯ Error:

TypeError: Reduce of empty array with no initial value

Link : TypeError: Reduce of Empty Array with No Initial Value (FixΒ Explained)


Best Practice

Always use initial value:

numbers.reduce((acc, curr) => acc + curr, 0);

Common Mistakes

1. Forgetting initial value

πŸ‘‰ Can cause errors


2. Using map() instead of reduce()

πŸ‘‰ Wrong approach for sum


3. Not understanding execution flow

πŸ‘‰ Leads to confusion in interviews


Real-World Use Cases

  • Shopping cart total
  • Marks calculation
  • Financial reports
  • Data aggregation

Interview Tip

If asked:

β€œHow does reduce work?”

Answer:

β€œIt iterates over each element, updates an accumulator value, and finally returns a single result.”


Related Articles (Internal Linking)

πŸ‘‰ You can also check:


Final Summary

  • reduce() converts array β†’ single value
  • acc stores result
  • curr is current element
  • Always use initial value (0)
  • Helps in writing clean and efficient code

πŸ’‘ Found this helpful? Subscribe to get simple JavaScript explanations, interview questions, and real-world coding tips directly in your inbox. Happy Coding!