React · Lesson 38 of 120
Dependencies
When effects run.
Running an effect after every render is often too much. The second argument, the dependency array, tells React when to run it again.
- Every render is too much
- Dependency array
- Run only when needed
Three kinds of effect
The first effect has an empty array, so it runs once, when the component first appears. The second lists name, so it runs only when name changes. We type two letters, then click the count button. Run it. The name effect ran for each letter, but not for the count.
App.jsxjsx
import { useState, useEffect } from "react";
export default function App() {
const [name, setName] = useState("");
const [count, setCount] = useState(0);
useEffect(() => console.log("once, on mount"), []);
useEffect(() => console.log("name changed:", name), [name]);
return (
<div>
<input id="n" value={name} onChange={e => setName(e.target.value)} placeholder="Name" />
<button id="c" onClick={() => setCount(count + 1)}>Count {count}</button>
</div>
);
}Output
once, on mount name changed: name changed: J name changed: Jo
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
[{"type": "#n", "text": "Jo"}, {"click": "#c"}]The dependency array
No array means after every render. An empty array means once, after the first render. An array of values means whenever one of them changes.
| Written | Runs |
|---|---|
| useEffect(fn) | after every render |
| useEffect(fn, []) | once, on mount |
| useEffect(fn, [a, b]) | when a or b changes |
Summary
The dependency array controls when an effect runs. List every value the effect uses. Next, cleanup.
Key takeaways- []
- [name]
- List what you use
Next up: Cleanup — timers and listeners