../courses.php
React
REACT107
90
Effects
Run code after React updates the screen.
When does a React component need an effect?
A React component needs an effect when it must synchronize with something outside normal rendering, such as fetching data, setting a document title, using browser storage, timers, or subscriptions.
Components render what the screen should look like.
State changes the component. Events usually cause state changes.
Sometimes a component must also do something outside the rendered JSX.
That outside work is called a side effect.
React uses useEffect for effects in function components.
Updating the document title with an effect
import { useEffect, useState } from "react";
function CounterTitle() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<section>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Add one
</button>
</section>
);
}
useEffect runs code after React renders.
document.title changes something outside the component's JSX.
[count] is the dependency list.
The effect runs again when count changes.
The button changes state, React renders, then the effect updates the browser tab title.
Outside systems
Effects connect React to browser APIs, servers, timers, and other systems.
Timing
Effects run after rendering, not while JSX is being calculated.
Control
The dependency list controls when the effect runs again.
Real apps
Data loading, document titles, storage, and subscriptions often use effects.
Doing side effects directly in render
function CounterTitle() {
document.title = "Changed during render";
return <h2>Counter</h2>;
}
Using an effect
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
Ask ChatGPT: "Is this work part of rendering, or is it a side effect that belongs in useEffect?" Then identify what outside system is being touched.
Import useEffect and useState.
Create a counter state value.
Use an effect to update document.title.
Put count in the dependency list.
Click the button and watch the browser tab title change.
Using effects for work that can be calculated during render.
Forgetting the dependency list.
Putting the wrong values in the dependency list.
Changing state inside an effect in a way that causes an infinite loop.
Touching outside systems directly inside the component render body.
Use React effects to synchronize a component with browser APIs or other outside systems after rendering.
Login - Jit4All
Login
Welcome back to Jit4All