Loading lessons...
Side Effects with useEffect
Side Effects with useEffect
React components are designed to be pure functions that map state and props to JSX. However, real-world apps need to perform side effects—tasks that interact with the outside world beyond rendering UI.
What is a Side Effect?
Examples of side effects in web applications include:
- Fetching data from an external REST API or GraphQL server
- Manually updating the DOM (e.g., updating
document.title) - Setting up timers or intervals (
setTimeout,setInterval) - Subscribing to external WebSocket connections or event listeners
The useEffect Hook
The useEffect hook lets you execute side-effect logic after React renders your component to the DOM.
import { useState, useEffect } from 'react';
function DocumentTitleUpdater() {
const [count, setCount] = useState(0);
// Runs after every render cycle
useEffect(() => {
document.title = "Clicked " + count + " times";
});
return (
<button onClick={() => setCount(count + 1)}>
Click count: {count}
</button>
);
}
Why Effects Run After Render
React defers running useEffect callbacks until after the browser paints the updated DOM tree. This ensures side effects do not block or slow down the initial visual rendering of the component.
Summary & TL;DR
- Side effects involve operations outside React's render lifecycle (fetching data, DOM mutation, timers).
- Import
useEffectfrom'react'. useEffectcallbacks run after React renders the component to the screen.