Sub topic 1
What Effects Are Actually For
Prerequisites
This chapter assumes you know function components, JSX, props, useState, and basic useEffect syntax. You should also know that changing state or props causes React to render again.
What Effects are actually for
An Effect synchronizes React with a system outside React. Examples include a network request, a browser API, a subscription, or a third-party widget. Effects run after React renders and commits the result to the screen.
An Effect is usually unnecessary when its only job is to calculate a value, respond to a click, or copy one piece of state into another.
Rendering is a calculation, not a place for side effects
Rendering should be pure. Given the same props and state, a component should calculate the same output without changing the outside world. Do not make network requests, change unrelated DOM nodes, or update state during rendering.
Use an event handler for work caused by an action such as clicking Submit. Use an Effect for synchronization caused by the component being displayed or by a value changing.
> callout note > An Effect is not a general-purpose “after render” callback. First identify the external system that React must synchronize with. > ```
Calculate values during render instead of syncing state
If one value can be calculated from existing props or state, calculate it during rendering. Storing it separately creates duplicate data and may require an unnecessary extra render.
import { useState } from 'react';
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
const fullName = firstName + ' ' + lastName;
return (
<>
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
<input value={lastName} onChange={e => setLastName(e.target.value)} />
<p>{fullName}</p>
</>
);
}Here, fullName is derived state: a value computed from other state. It does not need useState or useEffect.
Caching expensive calculations with useMemo
For a cheap calculation, calculate directly. For an expensive calculation that should repeat only when its inputs change, useMemo caches the result.
import { useMemo } from 'react';
function TodoList({ todos, filter }) {
const visibleTodos = useMemo(
() => todos.filter(todo => todo.status === filter),
[todos, filter]
);
return (
<ul>
{visibleTodos.map(todo => <li key={todo.id}>{todo.text}</li>)}
</ul>
);
}useMemo is a performance optimization, not a replacement for correct data flow. Do not add it automatically.
Exercise
Should an Effect store fullName after firstName or lastName changes?
Show answer
No. Calculate fullName during rendering because it is derived from existing state.