Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views5 pages

React State Test Plan - 2

useEffect is a React Hook that manages side effects in functional components, such as data fetching, DOM updates, and event listener management. It can be configured to run on every render, only on the first mount, or when specific state changes, with a cleanup function to prevent memory leaks. Best practices include using it for side effects, adding proper dependencies, and ensuring cleanup of subscriptions.

Uploaded by

sabidsabid77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

React State Test Plan - 2

useEffect is a React Hook that manages side effects in functional components, such as data fetching, DOM updates, and event listener management. It can be configured to run on every render, only on the first mount, or when specific state changes, with a cleanup function to prevent memory leaks. Best practices include using it for side effects, adding proper dependencies, and ensuring cleanup of subscriptions.

Uploaded by

sabidsabid77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

🔥 What is useEffect in React?

useEffect is a React Hook used to handle side effects in functional components.

🧠 Side Effects Include:


●​ Fetching data from an API​

●​ Updating the DOM manually​

●​ Setting up event listeners​

●​ Using setTimeout / setInterval​

●​ Working with localStorage​

●​ Subscribing and unsubscribing from services (like Firebase, sockets, etc.)​

✅ Basic Syntax:
useEffect(() => {
// code that runs after component mounts or updates
}, [dependencies]);

🧪 Example 1: Run on Every Render


useEffect(() => {
console.log("Component rendered!");
});

●​ No dependency array.​

●​ Runs after every render.​


🧪 Example 2: Run Only on First Mount
useEffect(() => {
console.log("Component mounted!");
}, []);

●​ Empty array means it runs only once, like componentDidMount in class components.​

🧪 Example 3: Run When Specific State Changes


useEffect(() => {
console.log(`Count is now ${count}`);
}, [count]);

●​ Runs every time count changes.​

📤 Example 4: Fetching Data


import { useEffect, useState } from "react";

function Users() {
const [users, setUsers] = useState([]);

useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => setUsers(data));
}, []); // run only once

return (
<div>
{users.map(user => <p key={user.id}>{user.name}</p>)}
</div>
);
}

🧹 Example 5: Cleanup Function


useEffect(() => {
const interval = setInterval(() => {
console.log("Tick");
}, 1000);

return () => {
clearInterval(interval); // cleanup
console.log("Interval cleared");
};
}, []);

●​ Cleanup runs when:​

○​ Component unmounts​

○​ Dependency changes (if any in array)​

🔄 Dependency Array Behavior


Dependency Array Behavior

[] Run once on mount

[var1, var2] Run when var1 or var2 changes


(no array) Run after every render

❗ Common Mistakes to Avoid


1.​ Infinite loop:​

useEffect(() => {
setCount(count + 1); // will keep running forever
}, [count]); // triggers again every time count changes

2.​ Not cleaning up effects:​

●​ Especially with intervals, subscriptions, or event listeners.​

3.​ Overusing useEffect:​

●​ Don’t put logic in useEffect if it can live inside the render or event handler.​

💡 Best Practices
✅ Do ❌ Avoid
Use useEffect for side effects Use it for pure rendering logic

Add proper dependencies Leave out dependencies

Always clean up subscriptions Let memory leaks happen

Fetch data inside useEffect Fetch data inside render body


🎯 Summary Table
Concept Description

useEffect(fn) Runs after every render

useEffect(fn, []) Runs only once (on mount)

useEffect(fn, Runs when dep changes


[dep])

Cleanup return Runs before component unmount or next effect

You might also like