The useEffect Hook for Side Effects
The useEffect Hook for Side Effects
1. What Are Side Effects?
A React component's primary job during rendering is pure: calculating the Virtual DOM representation for a given set of props and state.
However, modern applications frequently need to perform operations that reach outside the component's render scope:
- Fetching data from an external REST API
- Setting up a WebSocket connection or event subscription
- Manually interacting with browser APIs (e.g., modifying
document.titleor reading geolocation) - Setting timers (
setTimeout,setInterval) - Recording analytics page views
These operations are known as Side Effects (or simply "effects"). In React functional components, side effects are managed using the useEffect hook.
2. Anatomy of useEffect
The useEffect hook accepts two arguments:
- 1The Setup Function: The callback containing the side effect code. React executes this function after the browser has painted the DOM.
- 2The Dependency Array (Optional): An array of variables that dictates when the effect should re-run.
3. Basic Example: Synchronizing Document Title
4. Fetching Data with useEffect
When fetching data on initial component mount:
Note: The callback function passed to useEffect cannot be marked async directly (e.g. useEffect(async () => ...) is forbidden) because an async function returns a Promise, whereas React expects useEffect to return either a cleanup function or nothing!
Practice Quiz
useEffect callback function execute relative to the browser painting the screen?useEffect(async () => { ... }, [])?[] signify to useEffect?The Dependency Array and Execution Lifecycle
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Rules of React Hooks | The Dependency Array and Execution Lifecycle |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.