useEffect Hook in React
Imagine you're building a weather app. When the app first loads, you need to fetch weather data from an API. When the user searches for a different city, you need to fetch new data. And when the user navigates away from the weather page, you might want to cancel any pending requests. In React, all these "side effects" are handled by the **useEffect** hook.
What is the useEffect Hook?
`useEffect` is a React Hook that lets you perform side effects in functional components. Side effects are operations that affect something outside the component, such as:
- Fetching data from an API
- Directly manipulating the DOM (changing page title, focusing an input)
- Setting up subscriptions or timers
- Logging
`useEffect` combines the functionality of three class lifecycle methods: `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` into one powerful hook.
Basic Syntax
useEffect(() => { <!-- Side effect code goes here -->}, [dependencies]);`useEffect` takes two arguments:
- A function containing the side effect code.
- A dependency array (optional) that tells React when to re-run the effect.
When Does useEffect Run?
The behavior of `useEffect` depends on the dependency array:
| Dependency Array | When It Runs | Equivalent Lifecycle |
|---|---|---|
| No array | After every render | componentDidMount + componentDidUpdate |
| Empty array `[]` | Only on first render (mount) | componentDidMount |
| Array with values `[a, b]` | On mount and when a or b changes | componentDidUpdate for specific values |
Example 1: Run Once on Mount (componentDidMount)
import React, { useState, useEffect } from 'react';
function UserList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true);
useEffect(() => { <!-- This runs only once when component mounts --> fetch('https://jsonplaceholder.typicode.com/users') .then(response => response.json()) .then(data => { setUsers(data); setLoading(false); }); }, []); <!-- Empty dependency array -->
if (loading) return <div>Loading...</div>; return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> );}Example 2: Run When Dependencies Change (componentDidUpdate)
function DocumentTitle() { const [count, setCount] = useState(0);
<!-- Update document title whenever count changes --> useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); <!-- Run only when count changes -->
return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> );}Two Minute Drill
- `useEffect` is a React Hook for performing side effects in functional components.
- It takes a function (the effect) and an optional dependency array.
- With `[]` (empty array), the effect runs only once after the first render (mount).
- With `[dep1, dep2]`, the effect runs on mount and whenever any dependency changes.
- With no dependency array, the effect runs after every render.
- Common use cases: data fetching, DOM manipulation, subscriptions, timers.
Need more clarification?
Drop us an email at career@quipoinfotech.com
