useEffect Hook
The useEffect hook lets you perform side effects in functional components. Side effects include data fetching, manual DOM manipulation, and setting up subscriptions.
Syntax
`useEffect` takes a function as its first argument and an optional dependency array as the second.
JavaScript
useEffect(() => {
// Effect logic here
}, [dependencies]); Common Use Cases
- No Array: Runs after every render.
- Empty Array ([]): Runs only once after the initial render (like componentDidMount).
- With Dependencies: Runs only when the specified values change.
Data Fetching Example
Here is how you might fetch data when a component mounts.
JavaScript
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`https://api.example.com/users/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
}, [userId]); // Runs whenever userId changes
if (!user) return Loading...
;
return {user.name};
} Note: If your effect returns a function, React will run it when it's time to clean up (like before the component unmounts or before re-running the effect).