Managing Side Effects with useEffect
The `useEffect` hook manages side effects in React components, such as fetching data, subscribing to an event, or updating the DOM manually.
Key concepts
useEffect
A hook that manages side effects in React components, such as fetching data, subscribing to an event, or updating the DOM manually.
Step by step
How It Works:
- Effect: Runs after the component renders.
- Dependencies: Controls when the effect is executed.
- Empty Array (`[]`): Effect runs only once (like `componentDidMount`).
- Dependencies: Effect runs whenever the specified dependencies change.
When to Use:
- Fetching data from APIs.
- Subscribing to or cleaning up listeners.
- Performing manual DOM updates.
Examples
Fetching Data:
import React, { useState, useEffect } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.json())
.then((data) => setUsers(data));
}, []); // Runs only once
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus