React · Lesson 37 of 120
useEffect
Side effects.
Rendering should only work out what to show. But sometimes you need to reach outside React. Change the page title, start a timer, or fetch data. Those are side effects, and they go in use effect.
- Rendering: what to show
- Side effects: outside React
- useEffect
Updating the page title
Use effect takes a function. React runs it after the page has been drawn. Here it copies the basket count into the browser tab's title, and logs it. We click add twice. Run it.
App.jsxjsx
import { useState, useEffect } from "react";
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Basket (${count})`;
console.log("title is now", document.title);
});
return (
<div>
<p>Basket: {count} items</p>
<button id="add" onClick={() => setCount(count + 1)}>Add</button>
</div>
);
}Output
title is now Basket (0) title is now Basket (1) title is now Basket (2)
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#add", "times": 2}]After rendering
Effects run after React updates the page. So the screen is never held up by them. Without a second argument, an effect runs after every render. Next, we'll control that.
| key | value |
|---|---|
| Runs | after the page updates |
| Default | after every render |
| Use for | outside React |
| Not for | calculating values |
Summary
Use effect runs code that reaches outside React, after rendering. Next, dependencies.
Key takeaways- useEffect(fn)
- After render
- Side effects
Next up: Dependencies — when effects run