onMounted
onMounted runs a body once, at the end of the component’s first render, when
every element it draws exists and every prop is set.
onMounted(body: () => void): voidReference
Section titled “Reference”onMounted(body)
Section titled “onMounted(body)”A notice log that opens at its newest line.
export const NoticeLog = (): Component => { const log = useRef(); const [shown, setShown] = useState(3);
// Open at the newest line... onMounted(() => { log.scrollY = log.scrollHeight; }); // ...and stay on it as more arrive. onUpdated(() => { log.scrollY = log.scrollHeight; });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. Reading a ref’s geometry is legal here.
- Only after the first render. Every render after that is
onUpdated’s. Both may be written in one component. - A component that renders nothing on its first pass will mount again.
- The body takes no parameters (
TS2345). - Reads in the body do not subscribe. A cell read only here is allowed.
- A write the body makes through a ref is gone if the component is rebuilt, as every ref write is. A value that must persist is a cell.
onMounted((event) => { box.focus = true; }); // nothing to receiveOpening a log at the newest line
Section titled “Opening a log at the newest line” onMounted(() => { log.scrollY = log.scrollHeight; });The write is clamped, so this lands at the bottom.
Choosing between mount and update
Section titled “Choosing between mount and update”Alone, onMounted opens at the end once; add onUpdated to follow new lines.
Troubleshooting
Section titled “Troubleshooting”My hook ran twice
Section titled “My hook ran twice”The component drew nothing on its first pass — an empty conditional, or a
collection that produced no rows. Give the component
something it always draws, such as a full-size <layer> around the part that
may be empty.
The value I read in the body is stale
Section titled “The value I read in the body is stale”If the body should react to a value, the render should read it and hand the body the answer.