Chuyển đến nội dung

Bài 10 · Signals and Reactivity

Component Lifecycle: onMount and onCleanup

Learn the SolidJS component lifecycle: components run once, onMount runs after the DOM exists, onCleanup tears down, and how to use refs safely.

If you come from a framework that re-renders components, the Solid lifecycle is a relief: there are only two moments that matter, creation and disposal. A component function runs once. After that, only the small reactive expressions inside it update. This lesson shows the tools for those two moments: onMount and onCleanup.

Components run once

JavaScript
function Counter() {
  console.log("setup");              // printed once, ever
  const [n, setN] = createSignal(0);
  return <button onClick={() => setN(n() + 1)}>{n()}</button>;
}

"setup" prints one time when the component is created. Clicking the button does not run Counter again; it only updates the text node that reads n(). So the body of a component is the right place for setup work (creating signals, starting subscriptions), and you do not need "run once" guards or dependency arrays.

flowchart LR
    A["Component function runs once"] --> B["DOM nodes created and attached"]
    B --> C["onMount callbacks run"]
    C --> D["Signals change: small updates only"]
    D --> E["Component removed"]
    E --> F["onCleanup callbacks run"]

Lifecycle of a Solid component.

onMount

onMount(fn) runs fn once, after the component's elements are in the document. It is the place to measure elements, focus an input, or start a browser-only library.

JavaScript
function Search() {
  let input;
  onMount(() => input.focus());
  return <input ref={input} />;
}

onMount is an effect that tracks nothing, so reading signals inside it does not subscribe. It does not run during server-side rendering.

Focus and measure after mount

The body logs before the mount message, and by the time onMount runs the input exists, can be focused and has a real width. A ref is just an assignment that Solid performs while it builds the element.

onCleanup

onCleanup(fn) runs when the component is removed. Use it for anything you started: timers, window listeners, observers, sockets.

JavaScript
function Resize() {
  const [w, setW] = createSignal(window.innerWidth);
  const handler = () => setW(window.innerWidth);
  window.addEventListener("resize", handler);
  onCleanup(() => window.removeEventListener("resize", handler));
  return <p>{w()}px</p>;
}

The cleanup callbacks run in reverse order of registration, so later setup is undone first. See Ownership, Roots and Cleanup for how disposal reaches nested components.

A listener that is removed on unmount

Where lifecycle code goes

Task Where
Create signals, memos, derived functions Component body
Start a timer or subscription Component body or onMount, with onCleanup
Touch DOM nodes (focus, measure) onMount or a ref callback
Load a browser-only script onMount
Stop anything you started onCleanup
React to signal changes createEffect

Differences from other frameworks

  • No re-render lifecycle. There is nothing like "componentDidUpdate"; use an effect on the signals you care about.
  • No unmount flicker. Cleanup runs when the owner is disposed, including for subtrees removed by Show and For.
  • No dependency arrays. onMount is plain "once", and effects track automatically.
  • Server rendering. The body runs on the server and in the browser (on hydration), while onMount and effects run only in the browser.

Common mistakes

  • Reading ref in the body. The element is not attached yet; use onMount.
  • Starting a timer without onCleanup. It keeps running after the component is gone.
  • Expecting the body to re-run. If you need a value to update, make it a signal or a function.
  • Doing await before registering lifecycle callbacks. Register onMount and onCleanup synchronously.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How many times does a Solid component function run when its state changes?

    The function runs once; only the reactive expressions inside update.
  2. 2. When does onMount run?

    onMount is a run-once effect that fires after the DOM nodes exist.
  3. 3. Where do you remove a window event listener you added?

    onCleanup runs when the owner is disposed, which is the right place for removeEventListener.
  4. 4. Which is true about onMount during server-side rendering?

    Effects and onMount run only in the browser.

Summary

  • A component body runs once; there is no re-render cycle.
  • onMount runs after the DOM exists; use it for refs, focus and browser-only code.
  • onCleanup undoes whatever you started, when the owner is disposed.
  • React to later changes with createEffect, not with lifecycle hooks.

Next: JSX in Solid

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.