⚛️ React Hooks (useEffect useRef)
👉 Now you learn how React handles side effects and DOM access. These hooks are heavily used in real projects and interviews.
🧠 What are React Hooks
Hooks let you use React features inside functional components.
Before hooks → class components required
After hooks → functional components can do everything
✅ Common hooks
• useState → manage data
• useEffect → handle side effects
• useRef → access DOM or store values
🔄 Hook 1: useEffect (Side Effects)
❓ What is useEffect
useEffect runs code when:
✅ Component loads
✅ State changes
✅ Props change
✅ Component updates
Simple meaning 👉 Perform actions outside UI rendering.
📌 Why useEffect is needed
Used for:
• API calls
• Fetch data from server
• Timer setup
• Event listeners
• Page load logic
✍️ Basic Syntax
import { useEffect } from "react";
useEffect(() => {
// code to run
}, []);🚀 Run only once (on page load)
useEffect(() => {
console.log("Component mounted");
}, []);👉 Empty dependency array → runs once.
🔄 Run when state changes
useEffect(() => {
console.log("Count changed");
}, [count]);👉 Runs whenever count updates.
⏱️ Real Example — Timer
import { useState, useEffect } from "react";
function Timer() {
const [time, setTime] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setTime(t => t + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <h2>{time}</h2>;
}✔ Runs timer automatically
✔ Cleans memory using return
🎯 Hook 2: useRef (Access DOM / Store Values)
❓ What is useRef
useRef gives direct access to DOM elements. Also stores values without re-rendering.
Simple meaning 👉 Reference to element or value.
📌 Why useRef is used
• Focus input automatically
• Access DOM elements
• Store previous value
• Avoid re-render
✍️ Basic Syntax
import { useRef } from "react";
const inputRef = useRef();🎯 Example — Focus input automatically
import { useRef } from "react";
function InputFocus() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleFocus}>Focus</button>
</div>
);
}✔ Button click focuses input.
⚖️ useState, useEffect, and useRef — What's the difference?
• useState: Stores changing data that triggers re-renders.
• useEffect: Runs side effects (e.g., API calls, timers).
• useRef: Accesses DOM elements or stores values without re-rendering.
⚠️ Common Beginner Mistakes
• Forgetting dependency array in useEffect
• Infinite loops in useEffect
• Using useRef instead of state
• Not cleaning side effects
🧪 Mini Practice Task
• Print message when component loads using useEffect
• Create timer using useEffect
• Focus input automatically using useRef
• Store previous value using useRef
✅ Double Tap ♥️ For More