Lesson 13 / 25
When You Do Not Need an Effect
Most logic belongs in render or event handlers.
Common unnecessary effects
Effects are for synchronising with external systems. You do not need one to compute values from props or state (derive them during render, with useMemo if expensive), to respond to a user action (do it in the event handler), to reset state when a prop changes (use a key), or to chain state updates (compute the final state in one place). Unnecessary effects cause extra renders, flicker and bugs that are hard to trace.
Effect versus derived value
Not run here; a common refactor.
// Avoid: extra state + effect to keep it in sync
const [fullName, setFullName] = useState("");
useEffect(() => { setFullName(first + " " + last); }, [first, last]);
// Prefer: derive during render
const fullName = first + " " + last;
// Avoid: effect reacting to a submit flag
// Prefer: do the work in the submit handler
function handleSubmit() { sendOrder(cart); showToast("Order placed"); }Ask "is this syncing with something outside React?"
If not, you probably do not need an effect.
Quick check: Which case does NOT need an effect?
- Subscribing to a WebSocket
- Computing a full name from first and last name props
- Setting up a timer
- Integrating a non-React map widget
Answer
Computing a full name from first and last name props — Derive values during render.