
Useeffect in ReactJS
✅ useEffect
in ReactJS
The useEffect
hook in React is used to handle side effects in functional components. Side effects include tasks like data fetching, DOM manipulation, setting timers, or interacting with APIs.
🔎 Syntax
<h1>Hello, React!<ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> );}export default UserList;
Explanation:
fetchData()
is called once usinguseEffect
.The fetched data is stored using
setUsers()
.
✅ When to Use useEffect
Fetching data from APIs
Subscribing to services or events
Managing timers or intervals
Updating the document title
Performing cleanup actions
✅ Conclusion
useEffect(() => {})
→ Run on every render.useEffect(() => {}, [])
→ Run once on mount.useEffect(() => {}, [dependency])
→ Run when dependencies change.Return a function for cleanup to avoid memory leaks.