Sub topic 9
Notify Parents from the Event, Not from an Effect
This chapter assumes you know function components, useState, props, and the basic shape of useEffect with a dependency array. It also assumes you know that a state update causes a re-render. By the end, you should be able to spot an Effect that exists only to tell a parent "my state changed," and replace it with a call in the event handler.
The problem: a child that reports its state
Some components keep their own state but must also tell a parent about it. A toggle, a tab strip, a rating widget, and a search box all fit this description. The parent passes a callback prop such as onChange, and the child calls it when something happens.
A common first attempt uses an Effect to do the reporting:
import { useState, useEffect } from 'react';
function Toggle({ onChange }) {
const [isOn, setIsOn] = useState(false);
useEffect(() => {
onChange(isOn);
}, [isOn, onChange]);
function handleClick() {
setIsOn(!isOn);
}
return (
<button onClick={handleClick}>
{isOn ? 'On' : 'Off'}
</button>
);
}This looks reasonable. The Effect says "whenever isOn changes, tell the parent." It runs without errors in simple cases. It still has several problems, and they are easy to miss in a small example.
What actually happens
When the user clicks the button, React processes these steps:
handleClickcallssetIsOn.- React re-renders
Toggleand updates the screen. - After that render is committed, React runs the Effect.
- The Effect calls
onChange, which updates state in the parent. - React renders the parent and its children a second time.
The parent learns about the change one full render pass later than it could have. The user's click leads to two separate render passes, and the screen may be painted between them.
The diagram shows the order of events for the Effect version and the event handler version.
Why the Effect version is a problem
It uses an extra render pass
Each state update that happens inside an Effect triggers another render. React has to re-render the child, run the Effect, then re-render the parent tree. When the parent has expensive children, this repeated work is visible. Calling both updates from the event handler lets React batch them, so it renders once.
It can show an inconsistent screen
Between the first render and the Effect, the child already shows the new value while the parent still shows the old one. For one frame, two parts of the UI disagree. For a toggle this may not matter. For a form where the parent displays a total or a validation message based on the child's value, you can see flicker.
It runs for the wrong reasons
An Effect does not know why a value changed. It only sees that a dependency is different from last time. That causes some surprising behavior:
- On mount. The Effect runs once when the component first appears, so the parent gets an
onChange(false)call although nobody clicked anything. In development with Strict Mode, React also mounts, unmounts and mounts again, so the call can happen twice. - When
onChangechanges identity. The callback is in the dependency array. If the parent passes a new inline function on every render, the Effect re-runs on every render and callsonChangeeach time, even ifisOndid not change. This can become an infinite loop if the parent's handler sets state. - When state changes for another reason. If the parent later resets the child, for example through a prop or a
key, the Effect still reports the change as if the user did it.
You can try to patch these problems with refs, flags, or by removing onChange from the dependency array, but each patch makes the code harder to follow and hides a real dependency from the linter.
It makes the data flow hard to read
When the parent's state changes because of a child's Effect, you cannot find the cause by reading the click handler. You have to search for the Effect, work out which dependency triggered it, and then follow the callback. The event handler version reads in order: the user clicked, so this happens, and then that happens.
The fix: do both updates in the event handler
The change happened because the user clicked. So the code that reacts to the click belongs in the click handler. Update the child's state and call the parent's callback in the same function:
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>
);
}Now:
- The parent is notified at the moment of the click, with the exact value that the user chose.
- React batches
setIsOnand the parent's state update into one render pass. - There is no call on mount, no dependency array, and no sensitivity to the identity of
onChange. - The next value,
nextIsOn, is computed once and passed to both places, so the two cannot disagree.
Handling several ways to change the value
The event handler approach also helps when a component has more than one way to change its state. Suppose the toggle can also be dragged. You write one helper and call it from each handler:
import { useState } from 'react';
function Toggle({ onChange }) {
const [isOn, setIsOn] = useState(false);
function updateToggle(nextIsOn) {
setIsOn(nextIsOn);
onChange(nextIsOn);
}
function handleClick() {
updateToggle(!isOn);
}
function handleDragEnd(e) {
if (isCloseToRightEdge(e)) {
updateToggle(true);
} else if (isCloseToLeftEdge(e)) {
updateToggle(false);
}
}
return (
<div
role="switch"
aria-checked={isOn}
tabIndex={0}
onClick={handleClick}
onDragEnd={handleDragEnd}
>
{isOn ? 'On' : 'Off'}
</div>
);
}Every path that changes the value goes through updateToggle, so the parent cannot miss one. With the Effect version, you would get the same result, but only because the Effect watches the final state. The helper makes the intent explicit instead.
The helpers isCloseToRightEdge and isCloseToLeftEdge stand for your own hit-testing logic. They are not part of React.
A better option when you can: lift state up
Calling onChange from the handler removes the Effect, but the child and parent still each hold a copy of the value. Two copies of the same data can drift apart. If the parent really owns the value, the child should not have its own state for it. Make the component controlled:
function Toggle({ isOn, onChange }) {
function handleClick() {
onChange(!isOn);
}
function handleDragEnd(e) {
if (isCloseToRightEdge(e)) {
onChange(true);
} else if (isCloseToLeftEdge(e)) {
onChange(false);
}
}
return (
<div
role="switch"
aria-checked={isOn}
tabIndex={0}
onClick={handleClick}
onDragEnd={handleDragEnd}
>
{isOn ? 'On' : 'Off'}
</div>
);
}The parent holds isOn in its own useState and passes it down together with a setter. There is one source of truth, so nothing needs to be synchronized. Choose the controlled form when the parent needs to read or set the value. Keep the version with local state plus onChange when the child can work alone and the parent only wants to observe it.
| Approach | Who holds the state | Parent can set the value | Risk of two copies disagreeing |
|---|---|---|---|
| Effect that calls `onChange` | Child | No | Yes, briefly on every change |
| Handler calls `setIsOn` and `onChange` | Child | No | Low, both set in one pass |
| Controlled component | Parent | Yes | None |
Related case: the parent passes data down, the child passes data up
A similar mistake appears when a child fetches or computes something and then pushes it to the parent in an Effect:
function Child({ onFetched }) {
const data = useSomeAPI();
useEffect(() => {
if (data) {
onFetched(data);
}
}, [data, onFetched]);
return <p>Loading...</p>;
}Here the data flows upward through an Effect, which makes the flow hard to trace. In React, data flows down. When the parent needs the data, let the parent fetch it and pass it to the child as a prop. The data flow is then visible in the parent's code, and no Effect is needed to move it.
How to decide
Ask what caused the notification.
- If a specific user interaction caused it, such as a click, a keystroke, a drag, or a form submit, call the parent from that event handler.
- If the value can be computed from props and state, compute it during render and do not notify at all.
- If the parent should own the value, lift the state up and make the child controlled.
- If the cause is that the component appeared on screen, or that data from an external system changed, an Effect or
useSyncExternalStoremay be right. The next chapters cover those cases.
Edge cases
- State updates from timers or network responses. If the change came from a
setTimeoutor afetchcallback rather than a user event, there is no event handler to put the call in. CallonChangein the same callback where you call the setter. The rule is to notify from the code that caused the change, not from a later render. - Updater functions. If you compute the next value with
setCount(c => c + 1), you do not have the new value in hand. ComputenextCountfrom the currentcountfirst, then pass it to bothsetCountandonChange. Do not callonChangeinside an updater function, because React may call updater functions more than once in development to check that they are pure. - Derived notifications. If the parent needs a value derived from several child states, compute it in the handler from the next values, not from the stale ones in the closure.
Exercise
A Rating component keeps stars in local state and calls onRate(stars) from a useEffect with [stars, onRate] as dependencies. The parent logs an "analytics: user rated 0" event every time the page loads. What causes the extra log, and how do you fix it?
Show answer
The Effect runs after the first render, so it reports the initial value 0 although the user did nothing. Remove the Effect and call onRate(nextStars) in the click handler, right after setStars(nextStars). The parent is then notified only when the user rates.
Exercise
Why is onChange(isOn) called with a new inline arrow function from the parent likely to cause repeated calls when it sits inside an Effect that lists onChange as a dependency? What changes if the call moves to the event handler?
Show answer
An inline arrow function is a new function on every parent render, so the dependency changes each time, and the Effect runs again and calls onChange even though isOn did not change. If the call is in the event handler, it runs only when the event fires, so the identity of the callback no longer matters.
Exercise
When is it better to make the child a controlled component instead of keeping local state and calling onChange?
Show answer
When the parent needs to read or set the value, or when keeping two copies of the value risks them disagreeing. A controlled component receives the value and a change callback as props, so there is a single source of truth and no synchronization.