Skip to content

You Might Not Need an Effect

The Course
•
20 min study

Effects are for keeping something outside React in step: a timer, a connection, the network. They're often used for other things too, and each one costs an extra render and makes the code harder to follow. This board has three such effects. It logs render every time App renders:

JavaScript
console.log("render");

// 1. Keep the visible cards in step with the query.
useEffect(() => {
  setVisible(cards.filter((card) => card.title.toLowerCase().includes(query.toLowerCase())));
}, [cards, query]);

// 2. Clear the selection whenever the query changes.
useEffect(() => {
  setSelectedId(null);
}, [query]);

// 3. Say something when a card is added.
useEffect(() => {
  if (cards.length > starterCards.length) setMessage(`Added "${cards.at(-1).title}"`);
}, [cards]);
Three unnecessary effects React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards); const [query, setQuery] = useState(""); const [visible, setVisible] = useState(starterCards); const [selectedId, setSelectedId] = useState(null); const [message, setMessage] = useState(""); console.log("render"); // 1. Keep the visible cards in step with the query. useEffect(() => { setVisible(cards.filter((card) => card.title.toLowerCase().includes(query.toLowerCase()))); }, [cards, query]); // 2. Clear the selection whenever the query changes. useEffect(() => { setSelectedId(null); }, [query]); // 3. Say something when a card is added. useEffect(() => { if (cards.length > starterCards.length) setMessage(`Added "${cards.at(-1).title}"`); }, [cards]); return ( <main> <h1>Study Board</h1> <div className="toolbar"> <input aria-label="Search cards" placeholder="Search cards" value={query} onChange={(e) => setQuery(e.target.value)} /> <button onClick={() => setCards([...cards, { id: Date.now(), title: "New card", column: "todo", minutes: 15 }])}> Add a card </button> </div> {message && <p className="muted">{message}</p>} <ul className="cards"> {visible.map((card) => ( <li key={card.id} className={card.id === selectedId ? "card selected" : "card"}> <button className="title" onClick={() => setSelectedId(card.id)}>{card.title}</button> </li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Count the renders

Clear the console, type one letter in the search box, and count the render lines. Then do the same for Add a card.

What you'll see

Two renders for each. The first render shows the old visible cards, and only then does effect 1 copy the new list into state, which causes the second render. The page briefly shows stale data on every keystroke.

1. Values you can compute: compute them

Effect 1 copies a filtered list into visible. That's Day 1's derived value again. Delete the effect and the visible state, and compute it:

JavaScript
const visible = cards.filter((card) => card.title.toLowerCase().includes(query.toLowerCase()));

2. Resetting because of an event: do it in the handler

Effect 2 clears the selection "whenever the query changes". But the query only changes because the user typed. Do both at once, in the handler:

JavaScript
onChange={(e) => {
  setQuery(e.target.value);
  setSelectedId(null);
}}

React batches the two updates into one render. (When a whole component should start fresh because a prop changed, use a key, as on Day 1.)

3. Responding to a user action: do it in the handler

Effect 3 says "a card was added" by watching cards grow. It works by accident: it also fires if anything else ever makes cards longer, such as loading saved cards. The message is about the click, so put it in the click handler:

JavaScript
function addCard() {
  const card = { id: Date.now(), title: "New card", column: "todo", minutes: 15 };
  setCards([...cards, card]);
  setMessage(`Added "${card.title}"`);
}

Make all three changes. Now one keystroke, and one added card, each log one render, and there are no effects left.

The question to ask

Before writing an effect, ask why this code should run:

  • Because the component is on screen, and something outside React must match it (a subscription, a timer, a request): use an effect.
  • Because the user did something: put it in that event's handler.
  • Because some state or props changed, and you want another value: compute it during render.
Exercise

Which tool?

For each, say whether it belongs in an effect, an event handler, or the render.

  1. Showing 3 cards match under the search box.
  2. Sending an analytics event when someone presses Buy.
  3. Connecting to a chat room while a chat panel is open.
  4. Clearing a form after it's submitted.
  5. Setting the browser tab's title to the current card's name.
Hint 1: the idea

Identify what causes the work: a user event, external synchronization, or a calculation for the current screen.

Hint 2: a first step

Ask: does it react to the user doing something, to the component being shown, or is it just a value worked out from what's there?

Show one solution
  1. Render: it's computed from the matching cards.
  2. Event handler: it's caused by the click.
  3. Effect: an outside system kept in step while the panel is on screen, with a cleanup that disconnects.
  4. Event handler: the submit handler, after saving.
  5. Effect: document.title is outside React, and should follow whatever card is shown, however it got there.

Was this article helpful?

Your response is saved on this device.