Manipulating the DOM with useRef in React (Complete Guide with Examples)

When learning React, most developers use state and props to update the UI.

But sometimes, we need to directly access or manipulate a DOM element like:

  • Focusing an input
  • Playing a video
  • Scrolling to a section
  • Accessing element size

That’s where the useRef hook becomes very useful.

In this guide, you’ll learn:

  • What useRef is
  • Why we need it
  • How it manipulates the DOM
  • Best real-world examples
  • Common mistakes

What is useRef?

Simple Definition

useRef is a React hook that allows us to persist values and directly access DOM elements without re-rendering the component.


Syntax

const refName = useRef(initialValue);

How useRef Works

const inputRef = useRef(null);

React creates an object like:

{
current: null
}

When attached to an element:

<input ref={inputRef} />

inputRef.current now points to the actual DOM element.


Why Do We Need useRef?

Normally in React:

✅ UI updates through state

But sometimes we need:

  • Direct DOM access
  • Performance optimization
  • Persistent values without re-render

👉 useRef solves this.


Example 1: Focus Input Automatically

One of the most common use cases.

Code

import { useRef } from "react";

function App() {

const inputRef = useRef(null);

const focusInput = () => {
inputRef.current.focus();
};

return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>
Focus Input
</button>
</div>
);
}

export default App;

How It Works ?

Step 1

const inputRef = useRef(null);

Creates reference object.


Step 2

<input ref={inputRef} />

Connects DOM element to ref.


Step 3

inputRef.current.focus();

Directly accesses DOM element and focuses input.


Example 2: Change Background Color

Code

import { useRef } from "react";

function App() {

const boxRef = useRef(null);

const changeColor = () => {
boxRef.current.style.backgroundColor = "blue";
};

return (
<div>
<div
ref={boxRef}
style={{
width: "200px",
height: "200px",
background: "gray"
}}
/>
<button onClick={changeColor}>
Change Color
</button>
</div>
);
}

Example 3: Auto Scroll to Section

Very useful in landing pages.

Code

import { useRef } from "react";

function App() {

const sectionRef = useRef(null);

const scrollToSection = () => {
sectionRef.current.scrollIntoView({
behavior: "smooth"
});
};

return (
<div>
<button onClick={scrollToSection}>
Go to Section
</button>
<div style={{ height: "100vh" }} />
<div ref={sectionRef}>
Target Section
</div>
</div>
);
}

Example 4: Video Play/Pause Control

Code

import { useRef } from "react";

function App() {

const videoRef = useRef(null);

return (
<div>
<video
ref={videoRef}
width="400"
src="video.mp4"
/>
<button onClick={() => videoRef.current.play()}>
Play
</button>
<button onClick={() => videoRef.current.pause()}>
Pause
</button>
</div>
);
}

Example 5: Store Previous Value Without Re-render

Code

import { useEffect, useRef, useState } from "react";

function App() {
const [count, setCount] = useState(0);
const previousCount = useRef(0);

useEffect(() => {
previousCount.current = count;
}, [count]);

return (
<div>
<h2>Current: {count}</h2>
<h2>Previous: {previousCount.current}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}

Important Difference: useRef vs useState

FeatureuseRefuseState
Causes re-render❌ No✅ Yes
Stores value✅ Yes✅ Yes
Access DOM✅ Yes❌ No

Best Use Cases of useRef

Use useRef for:

✅ DOM access
✅ Focus management
✅ Scroll handling
✅ Timers
✅ Storing mutable values


Common Mistakes

❌ Manipulating DOM Too Much

React prefers declarative UI.

👉 Don’t overuse direct DOM manipulation.


❌ Accessing .current Before Render

console.log(ref.current);

May be null initially.


❌ Using useRef Instead of State

If UI must update → use state.


Interview Question

❓ What is useRef in React?

👉 Answer:

useRef is a hook used to persist values across renders and directly access DOM elements without causing re-renders.


Final Summary

  • useRef gives direct DOM access
  • Does not trigger re-render
  • Useful for focus, scroll, video control, timers
  • Should be used carefully

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

Do AI Tools Like ChatGPT Read Your Blog? How AI Actually Uses Website Content

With the rise of AI tools like ChatGPT, GitHub Copilot, and Google Gemini, many bloggers and developers have an important question:

🤔 “Is AI reading my blog posts and showing my content to users?”

Let’s understand this clearly — without confusion.


Short Answer

👉 Yes and No

AI can use information from websites, but:

❗ It does NOT work like Google search showing your exact blog link every time.


How AI Actually Works

AI models are trained using:

  • Large datasets
  • Publicly available text
  • Licensed data
  • Human-created content

👉 This includes content from:

  • Articles
  • Blogs
  • Documentation

Important Point

AI does NOT “remember” your blog as a specific page

👉 Instead:

  • It learns patterns
  • Understands concepts
  • Generates new responses

Does AI Read Your Blog in Real-Time?

❌ Not Always

Most AI tools:

  • Do NOT visit your website live
  • Do NOT fetch your blog every time

But Sometimes (Important)

Some AI systems can:

  • Access real-time data
  • Use browsing tools
  • Fetch web results

👉 In those cases:

👉 YES — your blog can be read and used


How AI Uses Website Content


🔹 1. During Training

AI learns from:

  • Public content
  • Documentation
  • Articles

👉 Your blog may contribute to training knowledge


2. During Live Queries (Some Tools)

Some AI tools:

  • Search the web
  • Extract relevant content
  • Summarize it

👉 This is similar to search engines


3. Through RAG (Advanced Systems)

Modern AI uses:

Retrieval-Augmented Generation (RAG)

👉 Process:

  1. User asks question
  2. AI searches relevant content
  3. Fetches data from sources
  4. Generates answer

👉 In this case:

✔ Your blog can be used
✔ Your content becomes part of the answer


Are You Getting Traffic from AI?

👉 Here’s the honest truth:


❌ Not Always Direct Traffic

AI usually:

  • Summarizes content
  • Doesn’t always give your link

✅ But You Still Benefit

Your content helps:

  • Train AI systems
  • Improve knowledge quality
  • Influence generated answers

Growing Trend (Important)

New AI tools are starting to:

  • Show sources
  • Provide links
  • Credit websites

👉 This means:

💡 AI can become a traffic source in the future


Correct Thinking

  • AI uses web content
  • Your blog can contribute
  • Your content has value

But Clarification

  • AI is not guaranteed to send traffic
  • It doesn’t always cite your blog
  • It may generate answers without linking

What Should Content Writers Do?

1. Focus on Quality Content

  • Clear explanations
  • Real examples
  • Unique insights

2. Write for Humans First

AI may use content, but:

👉 Humans still read your blog


3. Build Authority

  • Consistent posting
  • Niche expertise

4. Optimize for Search Engines

👉 SEO still matters


Future of AI and Blogging

The future is shifting toward:

  • AI + Search combined
  • More source attribution
  • Better visibility for creators

💡 “Good content will always win — whether through search engines or AI.”


Final Thoughts

  • AI can use content from blogs
  • It may not always give direct traffic
  • Your content still matters

👉 So keep writing, improving, and sharing knowledge.

Because:

Even if users don’t always visit your blog, your content is shaping the knowledge AI provides.


💡 If this content is helpful, please subscribe. Keep learning, keep sharing, and happy coding!

Skip One, Sum the Rest: A Smart JavaScript Array Trick

When working with arrays in JavaScript, we often need to calculate the total sum of elements. But what if you want to exclude one specific index while summing?

Let’s understand this with a simple and practical example.


Problem Statement

Given an array:

const a = [1, 2, 3, 4];

If we exclude index 2, the value 3 should be ignored.

👉 So the result becomes:

1 + 2 + 4 = 7

Approach

We need to:

  1. Loop through the array
  2. Skip the given index
  3. Add all other values

Solution 1: Using for Loop (Beginner Friendly)

function sumExceptIndex(arr, excludeIndex) {
let sum = 0;

for (let i = 0; i < arr.length; i++) {
if (i !== excludeIndex) {
sum += arr[i];
}
} return sum;
}

// Example
const a = [1, 2, 3, 4];
console.log(sumExceptIndex(a, 2)); // 7

✔️ Why this works:

  • We check i !== excludeIndex
  • Only add values that don’t match the excluded index

Solution 2: Using reduce() (Modern JavaScript)

function sumExceptIndex(arr, excludeIndex) {
return arr.reduce((sum, current, index) => {
return index !== excludeIndex ? sum + current : sum;
}, 0);
}

// Example
const a = [1, 2, 3, 4];
console.log(sumExceptIndex(a, 2)); // 7

Why this is powerful:

  • Cleaner and shorter
  • Uses functional programming style
  • Great for interviews and real-world code

Bonus: Random Index Exclusion

Want to make it dynamic?

const a = [1, 2, 3, 4];
const randomIndex = Math.floor(Math.random() * a.length);
const result = sumExceptIndex(a, randomIndex);
console.log("Excluded Index:", randomIndex);
console.log("Result:", result);

Real-World Analogy

Imagine you and your friends are splitting a bill:

  • Total items: [1, 2, 3, 4]
  • One friend didn’t order anything (index 2 → value 3)

So you calculate the bill excluding that friend’s item.

👉 That’s exactly what we’re doing in code!


Edge Cases to Consider

  • ❌ Invalid index (negative or out of range)
  • ❌ Empty array
  • ❌ Non-number values inside array

👉 You can improve your function by adding validations.


Improved Version with Validation

function sumExceptIndex(arr, excludeIndex) {
if (!Array.isArray(arr)) return 0;
if (excludeIndex < 0 || excludeIndex >= arr.length) return 0;
return arr.reduce((sum, val, index) => {
if (typeof val !== "number") return sum;
return index !== excludeIndex ? sum + val : sum;
}, 0);
}

🎉 Conclusion

This simple problem teaches you:

  • How to loop through arrays
  • How to skip elements based on conditions
  • How to use powerful methods like reduce()

Small problems like this build strong fundamentals in JavaScript.

Stay Connected

If you found this helpful and want to learn more practical JavaScript tricks like this:

👉 Subscribe to the blog for simple, real-world coding tips that actually make you a better developer.

  • No fluff
  • Just useful concepts
  • Beginner to advanced clarity

💡 Don’t miss the next post—you might learn something that saves hours of debugging!

Don’t Depend Too Much on AI for Coding — It Can Kill Your Skills

AI tools like GitHub Copilot and ChatGPT are changing how we write code.

They help us:

  • Write faster
  • Debug quicker
  • Learn new concepts

But there’s a serious problem many developers are ignoring:

⚠️ Over-dependence on AI can slowly kill your thinking ability.


⚠️ The Hidden Problem

If you use AI tools for everything:

  • Writing code
  • Fixing bugs
  • Understanding logic

👉 Your brain starts doing less work.

Over time:

❌ You stop thinking deeply
❌ You stop solving problems on your own
❌ You rely on suggestions instead of logic


What Happens in the Long Run?

❌ 1. You Lose Problem-Solving Skills

Coding is not about typing code.

It’s about:

  • Thinking
  • Breaking problems
  • Designing solutions

👉 AI removes that struggle — and that’s dangerous.


❌ 2. You Become Dependent

Imagine this:

👉 You’ve been using AI tools daily for months or years

Now suddenly:

  • AI is down ❌
  • No internet ❌
  • Tool not available ❌

👉 What happens?

⚠️ You feel completely blocked.

Even if you knew the concept before…
👉 your brain is no longer used to thinking without help.


❌ 3. False Confidence

AI gives answers quickly.

👉 You feel productive
👉 You feel skilled

But in reality:

❌ You didn’t solve the problem — AI did


❌ 4. Weak Debugging Skills

When something breaks:

👉 You don’t know:

  • Why it happened
  • How to fix it
  • Where to look

Real Truth

💡 AI is powerful — but it should assist your thinking, not replace it.


Developer Mindset You Must Follow

Think like this:

👉 AI = Assistant
👉 YOU = Developer (Decision Maker)


Use AI for:

  • Suggestions
  • Speed
  • Learning

Don’t use AI for:

  • Blind copy-paste
  • Every small problem
  • Thinking replacement

Balanced Approach (Best Practice)

Step 1: Try Yourself First

  • Think about solution
  • Write your approach

Step 2: Use AI

  • Compare solutions
  • Improve your code

Step 3: Understand It

  • Why this works?
  • Can I explain this?

Warning Sign You Are Overdependent

Ask yourself:

  • Can I solve problems without AI?
  • Do I understand what I copy?
  • Can I debug without help?

👉 If “NO” → you are becoming dependent


Strong Advice (Very Important)

💡 “Don’t let your brain become lazy because of powerful tools.”


Final Thoughts

AI is not the enemy.

But blind dependency is.

✔ Use AI wisely
✔ Keep your thinking active
✔ Practice problem-solving

Because in the long run:

💡 Your skill is your real asset — not the tool you use.


💡 If this post made you think, subscribe for more real developer insights. Build skills, not dependency. Happy Coding!

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!