Sub topic 9
Notify parents from the event, not from an Effect
This chapter assumes you know function components, useState, props, and the basics of useEffect with a dependency array. It covers one pattern: how a child component tells its parent that something changed.
The problem: an Effect that calls the parent
A Toggle component keeps its own isOn state. The parent also wants to know when it changes, so the parent passes an onChange callback. A common first attempt calls that callback from an Effect:
import { useState, useEffect } from 'react';
function Toggle({ onChange }) {
const [isOn, setIsOn] = useState(false);
// Avoid: the Effect runs after the render has already been shown.
useEffect(() => {
onChange(isOn);
}, [isOn, onChange]);
function handleClick() {
setIsOn(!isOn);
}
return <button onClick={handleClick}>{isOn ? 'On' : 'Off'}</button>;
}This looks reasonable, but it has several problems.
- Extra render pass. The click updates
isOn, and React renders and paintsToggle. Only then does the Effect run and call the parent, which sets its own state and renders again. The user can briefly see a screen where the child and parent disagree. - It runs when nobody clicked. The Effect also runs on mount. The parent receives
onChange(false)although the user did nothing. - It depends on
onChange. If the parent passes a new function on every render, the Effect re-runs each time and calls the parent again. If you leaveonChangeout of the dependency array to avoid this, you hide a real dependency.
The root cause is that the notification is not caused by rendering. It is caused by a click. Effects are for synchronizing with outside systems, and a user action is not a reason to run one.
The fix: do both updates in the event handler
Update the local state and call the parent in the same handler:
import { useState } from 'react';
function Toggle({ onChange }) {
const [isOn, setIsOn] = useState(false);
function updateToggle(nextIsOn) {
setIsOn(nextIsOn);
onChange(nextIsOn);
}
return (
<button onClick={() => updateToggle(!isOn)}>
{isOn ? 'On' : 'Off'}
</button>
);
}React batches state updates made in the same event. The child's setIsOn and whatever state the parent sets inside onChange are applied in a single render pass. Nothing runs on mount, because no click happened. onChange is not a dependency of anything, so a changing function identity is harmless.
Notice that updateToggle takes the next value as an argument. It does not read isOn after calling setIsOn, because state inside a handler is a snapshot from the current render and does not change until the next render.
Going further: lift the state up
The handler version still stores the same fact in two places: the child's isOn and whatever the parent keeps. Two copies can drift apart. If the parent genuinely needs the value, let it own the state and make the child controlled:
import { useState } from 'react';
function Toggle({ isOn, onChange }) {
return (
<button onClick={() => onChange(!isOn)}>
{isOn ? 'On' : 'Off'}
</button>
);
}
export default function Panel() {
const [isOn, setIsOn] = useState(false);
return (
<>
<Toggle isOn={isOn} onChange={setIsOn} />
<p>The lamp is {isOn ? 'on' : 'off'}.</p>
</>
);
}Now there is one source of truth and no notification step at all. Choose between the two versions like this:
| Situation | Pattern |
|---|---|
| Only the child needs the value, the parent just reacts to events | Child keeps state and calls `onChange` in the handler |
| Parent also displays or uses the value | Lift state up, make the child controlled |
| Child should work with or without a parent controlling it | Support both, as built-in inputs do |
Common errors
- Adding
onChangeto an Effect's dependency array and then wrapping the parent's callback inuseCallbackto stop re-runs. The workaround treats a symptom. Move the call into the handler instead. - Calling
onChange(isOn)right aftersetIsOn(!isOn). This sends the old value. ComputenextIsOnonce and use it for both calls. - Using an Effect to notify the parent when the cause is not a user event, such as a timer or a subscription. There the Effect may be the right place, because the change comes from a system outside React.
Exercise
A SearchBox child keeps text in state and has an Effect that calls props.onSearch(text) whenever text changes. The parent logs a search on mount, before the user types anything. Why does this happen, and how do you fix it?
Show answer
The Effect runs after the first render as well as after changes, so it calls onSearch('') on mount. The notification is caused by typing, not by rendering. Remove the Effect and call setText(next) and onSearch(next) together in the input's onChange handler, using the same next value for both. If the parent also needs the text, lift text into the parent instead.