onUpdated
onUpdated runs a body at the end of every render of a component except its
first — after the patch, when every element exists and every prop is set.
onUpdated(body: () => void): voidReference
Section titled “Reference”onUpdated(body)
Section titled “onUpdated(body)”A log that follows its newest line. Growing scrollHeight does not move
scrollY.
// Open at the newest line... onMounted(() => { log.scrollY = log.scrollHeight; }); // ...and stay on it as more arrive. onUpdated(() => { log.scrollY = log.scrollHeight; }); <layer ref={log} x={4} y={2} w={{ fill: 8 }} h={{ fill: 4 }} scrollHeight={shown * ROW_H}> {MESSAGES.map((line, i) => i < shown && ( <text x={0} y={i * ROW_H} w="fill" h={ROW_H} text={line} font={Fonts.SMALL} valign="middle" shadow color={i === shown - 1 ? Colors.WHITE : Colors.DIM} /> ))} </layer>Parameters
Section titled “Parameters”body: A function taking no arguments. No dependency array, no cleanup return.
Returns
Section titled “Returns”Nothing.
Caveats
Section titled “Caveats”- It runs at the very end of the render, after the patch. Reading a ref’s geometry is legal here.
- After every render but the first. For the first, use
onMounted. - An effect subscribes to nothing, so a cell the render bound and only
this body reads is refused (
TS2E218). Derive what the body applies in the render, and hand it the answer. - The body takes no parameters (
TS2345).
const plate = useRef(); const [open, setOpen] = useState(0);
onUpdated(() => { plate.hide = open === 0; }); // `open` is read only hereFollowing a growing list
Section titled “Following a growing list” onUpdated(() => { log.scrollY = log.scrollHeight; });Keeping a view inside contents that shrank
Section titled “Keeping a view inside contents that shrank”When the contents shrink, write the offset back to clamp it:
log.scrollY = log.scrollY.
Troubleshooting
Section titled “Troubleshooting”My hook does not run when the panel opens
Section titled “My hook does not run when the panel opens”The first render is
onMounted’s. Write both if you want
both.
My hook never runs at all
Section titled “My hook never runs at all”Nothing the component reads changed, so it never rendered again. See How updates happen.
A cell is “read only inside onUpdated”
Section titled “A cell is “read only inside onUpdated””Read it in the render — into the prop it decides, or into a local the body uses.