Skip to content

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): void

A notice log that opens at its newest line.

src/reference-lifecycle.ts2
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; });
  • body: A function taking no arguments. No dependency array, no cleanup return.

Nothing.

  • 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.
refused/on-mounted.ts2
onMounted((event) => { box.focus = true; }); // nothing to receive
src/reference-lifecycle.ts2
onMounted(() => { log.scrollY = log.scrollHeight; });

The write is clamped, so this lands at the bottom.

Alone, onMounted opens at the end once; add onUpdated to follow new lines.

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.

If the body should react to a value, the render should read it and hand the body the answer.