# Lifecycle

> onMounted runs once the component's DOM is in the document, onUnmounted when it's removed, and nextTick waits for the DOM to update. None runs on the server.

A component's setup runs before its DOM exists, and on the server too. `onMounted` runs code once the component's elements are in the document, and `onUnmounted` once they are removed. In client code, `await nextTick()` waits until the DOM shows the writes made before it. All three run in the browser only, on every target.

## onMounted

`onMounted(callback)` runs once, after the component's DOM is in the document. It can read an element through a template ref, write state and emit:

<!-- prettier-ignore -->
```tsx [ArticlePreview.uf.tsx]
import { defineEmits, onMounted, ref, useTemplateRef } from "@uxfront/unframework";

export interface ArticlePreviewProps {
  title: string;
  text: string;
}

export default function ArticlePreview({ title, text }: ArticlePreviewProps) {
  const emit = defineEmits<{ ready: [characters: number] }>();

  const body = useTemplateRef<HTMLParagraphElement>();
  const characters = ref(0);
  const counted = ref(false);

  onMounted(() => {
    const length = body.value?.textContent?.length ?? 0;
    characters.value = length;
    counted.value = true;
    emit("ready", length);
  });

  return (
    <article class="article-preview" aria-label={title}>
      <h2>{title}</h2>
      <p ref={body}>{text}</p>
      <p role="status">
        {counted.value ? `${characters.value} characters` : "Counting the characters"}
      </p>
    </article>
  );
}
```

Each framework gets its own mount hook:

::framework-switcher
#react

<!-- prettier-ignore -->
```tsx [ArticlePreview.tsx]
import { type CSSProperties, useEffect, useEffectEvent, useRef, useState } from "react";

export interface ArticlePreviewProps {
  title: string;
  text: string;
}

export interface ArticlePreviewEvents {
  onReady?: (characters: number) => void;
}

export interface ArticlePreviewAttributes {
  className?: string;
  style?: CSSProperties;
}

export default function ArticlePreview({
  title,
  text,
  onReady,
  className,
  style,
  ...attributes
}: ArticlePreviewProps & ArticlePreviewEvents & ArticlePreviewAttributes) {
  const body = useRef<HTMLParagraphElement>(null);
  const [characters, setCharacters] = useState(0);
  const charactersRef = useRef(characters);
  const [counted, setCounted] = useState(false);
  const countedRef = useRef(counted);

  const onMount = useEffectEvent(() => {
    const length = body.current?.textContent?.length ?? 0;
    charactersRef.current = length;
    setCharacters(charactersRef.current);
    countedRef.current = true;
    setCounted(countedRef.current);
    onReady?.(length);
  });
  useEffect(() => {
    onMount();
  }, []);

  return (
    <article
      className={cx("article-preview", className)}
      aria-label={title}
      style={style}
      {...scopeAttributes(attributes)}
    >
      <h2>{title}</h2>
      <p ref={body}>{text}</p>
      <p role="status">{counted ? `${characters} characters` : "Counting the characters"}</p>
    </article>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#vue

<!-- prettier-ignore -->
```vue [ArticlePreview.vue]
<script setup lang="ts">
import { onMounted, ref, useTemplateRef } from "vue";

export interface ArticlePreviewProps {
  title: string;
  text: string;
}

const { title, text } = defineProps<ArticlePreviewProps>();
const emit = defineEmits<{ ready: [characters: number] }>();

const body = useTemplateRef<HTMLParagraphElement>("body");
const characters = ref(0);
const counted = ref(false);

onMounted(() => {
  const length = body.value?.textContent?.length ?? 0;
  characters.value = length;
  counted.value = true;
  emit("ready", length);
});
</script>

<template>
  <article class="article-preview" :aria-label="title">
    <h2>{{ title }}</h2>
    <p ref="body">{{ text }}</p>
    <p role="status">{{ counted ? `${characters} characters` : "Counting the characters" }}</p>
  </article>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [ArticlePreview.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts" module>
  export interface ArticlePreviewProps {
    title: string;
    text: string;
  }
</script>

<script lang="ts">
  import { onMount } from "svelte";
  import type { ClassValue } from "svelte/elements";

  type Props = ArticlePreviewProps & {
    onready?: (characters: number) => void;
    class?: ClassValue;
    style?: string;
  };

  let { title, text, onready, class: className, style, ...attributes }: Props = $props();

  let body: HTMLParagraphElement | null = null;
  let characters = $state(0);
  let counted = $state(false);

  onMount(() => {
    const length = body?.textContent?.length ?? 0;
    characters = length;
    counted = true;
    onready?.(length);
  });

  /** The scope attributes of the styled parents that render this component, for its root. */
  function scopeAttributes(props: object): Record<string, ""> {
    const scope: Record<string, ""> = {};
    for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
    return scope;
  }
</script>

<article
  class={["article-preview", className]}
  aria-label={title}
  {style}
  {...scopeAttributes(attributes)}
>
  <h2>{title}</h2
  ><p bind:this={body}>{text}</p
  ><p role="status">{counted ? `${characters} characters` : "Counting the characters"}</p>
</article>
```

#angular

<!-- prettier-ignore -->
```ts [article-preview.ts]
import {
  Component,
  Directive,
  ElementRef,
  type OnInit,
  Renderer2,
  afterNextRender,
  inject,
  input,
  output,
  signal,
  viewChild,
} from "@angular/core";

export interface ArticlePreviewProps {
  title: string;
  text: string;
}

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

@Component({
  selector: "uf-article-preview",
  imports: [ScopeAttributes],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let title = this.title();
    @let text = this.text();
    @let characters = this.characters();
    @let counted = this.counted();
    <article
      class="article-preview"
      [attr.aria-label]="title"
      [class]="this.class()"
      [style]="this.style()"
      [ufScope]="this.host"
    >
      <h2>{{ title }}</h2>
      <p #body>{{ text }}</p>
      <p role="status">{{ counted ? characters + " characters" : "Counting the characters" }}</p>
    </article>
  `,
})
export default class ArticlePreview {
  readonly title = input.required<string>();
  readonly text = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ready = output<number>();
  private readonly body = viewChild<ElementRef<HTMLParagraphElement>>("body");
  protected readonly characters = signal(0);
  protected readonly counted = signal(false);

  constructor() {
    afterNextRender(() => {
      const length = this.body()?.nativeElement.textContent?.length ?? 0;
      this.characters.set(length);
      this.counted.set(true);
      this.ready.emit(length);
    });
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [ArticlePreview.tsx]
import { type JSX, createSignal, onCleanup, onMount } from "solid-js";

export interface ArticlePreviewProps {
  title: string;
  text: string;
}

export interface ArticlePreviewEvents {
  onReady?: (characters: number) => void;
}

export default function ArticlePreview(
  props: ArticlePreviewProps & ArticlePreviewEvents & { class?: string; style?: JSX.CSSProperties },
) {
  let body: HTMLParagraphElement | null = null;
  const [characters, setCharacters] = createSignal(0);
  const [counted, setCounted] = createSignal(false);

  onMount(() => {
    const length = body?.textContent?.length ?? 0;
    setCharacters(length);
    setCounted(true);
    props.onReady?.(length);
  });

  return (
    <article
      class={props.class ? `article-preview ${props.class}` : "article-preview"}
      aria-label={props.title}
      style={props.style}
      {...scopeAttributes(props)}
    >
      <h2>{props.title}</h2>
      <p
        ref={(element) => {
          body = element;
          onCleanup(() => {
            body = null;
          });
        }}
      >
        {props.text}
      </p>
      <p role="status">{counted() ? `${characters()} characters` : "Counting the characters"}</p>
    </article>
  );
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
```

#qwik

<!-- prettier-ignore -->
```tsx [ArticlePreview.tsx]
import {
  type CSSProperties,
  type ClassList,
  type QRL,
  component$,
  useSignal,
  useVisibleTask$,
} from "@qwik.dev/core";

export interface ArticlePreviewProps {
  title: string;
  text: string;
}

export interface ArticlePreviewEvents {
  onReady$?: QRL<(characters: number) => void>;
}

export default component$<
  ArticlePreviewProps & ArticlePreviewEvents & { class?: ClassList; style?: CSSProperties }
>(({ title, text, onReady$, class: className, style, ...attributes }) => {
  const body = useSignal<HTMLParagraphElement>();
  const characters = useSignal(0);
  const counted = useSignal(false);

  useVisibleTask$(
    () => {
      const length = body.value?.textContent?.length ?? 0;
      characters.value = length;
      counted.value = true;
      onReady$?.(length);
    },
    { strategy: "document-ready" },
  );

  return (
    <article
      class={["article-preview", className]}
      aria-label={title}
      {...scopeAttributes(attributes)}
      style={style}
    >
      <h2>{title}</h2>
      <p ref={body}>{text}</p>
      <p role="status">
        {counted.value ? `${characters.value} characters` : "Counting the characters"}
      </p>
    </article>
  );
});

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#astro

<!-- prettier-ignore -->
```astro [ArticlePreview.astro]
---
export interface ArticlePreviewProps {
  title: string;
  text: string;
}

interface Props extends ArticlePreviewProps {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { title, text, class: className, style } = Astro.props;

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}

const characters = 0 as number;
const counted = false as boolean;
---

<article
  class:list={["article-preview", className]}
  aria-label={title}
  style={style}
  {...scopeAttributes(Astro.props)}
>
  <h2>{title}</h2>
  <p>{text}</p>
  <p role="status">{counted ? `${characters} characters` : "Counting the characters"}</p>
</article>
```

::

- React writes an effect with an empty list of dependencies, which runs the callback once, in an effect event.
- Vue writes `onMounted`, Svelte and Solid `onMount`.
- Angular writes `afterNextRender` in the constructor: it runs once the view is rendered, in the browser only.
- Qwik writes `useVisibleTask$` with the `"document-ready"` strategy, so the task runs once the document is ready, not when the element scrolls into view.
- Astro drops the hook, and renders the state it starts with.

A hook never runs on the server, so every target's server render shows the state before it: "Counting the characters". The browser then shows the count. A new value for a prop does not run the hook again.

`onMounted` and `onUnmounted` take an arrow function written in place: `onMounted(focusField)` is [UF2022](/docs/reference/diagnostics#UF2022), with a safe fix to `onMounted(() => focusField())`. They are called at the top level of the setup ([UF2005](/docs/reference/diagnostics#UF2005)), never inside a condition or another hook.

## onUnmounted

`onUnmounted(callback)` runs once the component is removed. It stops what the component started, such as a timer held in a setup `let`:

<!-- prettier-ignore -->
```tsx [AutoRefresh.uf.tsx]
import { defineEmits, onUnmounted, ref } from "@uxfront/unframework";

export interface AutoRefreshProps {
  /** Milliseconds between two refreshes. */
  interval: number;
}

export default function AutoRefresh({ interval }: AutoRefreshProps) {
  const emit = defineEmits<{ refresh: [count: number] }>();

  const enabled = ref(false);
  let timer: ReturnType<typeof setInterval> | undefined;
  let refreshes = 0;

  function tick() {
    refreshes += 1;
    emit("refresh", refreshes);
  }

  function toggle() {
    if (enabled.value) {
      clearInterval(timer);
      enabled.value = false;
    } else {
      timer = setInterval(tick, interval);
      enabled.value = true;
    }
  }

  onUnmounted(() => {
    clearInterval(timer);
  });

  return (
    <section class="auto-refresh" aria-label="Auto-refresh">
      <button type="button" aria-pressed={enabled.value} onClick={toggle}>
        Auto-refresh
      </button>
      <p role="status">{enabled.value ? "Refreshing" : "Paused"}</p>
    </section>
  );
}
```

::framework-switcher
#react

<!-- prettier-ignore -->
```tsx [AutoRefresh.tsx]
import {
  type CSSProperties,
  useEffect,
  useEffectEvent,
  useLayoutEffect,
  useRef,
  useState,
} from "react";

export interface AutoRefreshProps {
  /** Milliseconds between two refreshes. */
  interval: number;
}

export interface AutoRefreshEvents {
  onRefresh?: (count: number) => void;
}

export interface AutoRefreshAttributes {
  className?: string;
  style?: CSSProperties;
}

export default function AutoRefresh({
  interval,
  onRefresh,
  className,
  style,
  ...attributes
}: AutoRefreshProps & AutoRefreshEvents & AutoRefreshAttributes) {
  const onRefreshRef = useRef(onRefresh);
  useLayoutEffect(() => {
    onRefreshRef.current = onRefresh;
  });

  const [enabled, setEnabled] = useState(false);
  const enabledRef = useRef(enabled);
  const timer = useRef<ReturnType<typeof setInterval> | undefined>(undefined);
  const refreshes = useRef(0);

  const [tick] = useState(() => () => {
    refreshes.current += 1;
    onRefreshRef.current?.(refreshes.current);
  });

  function toggle() {
    if (enabledRef.current) {
      clearInterval(timer.current);
      enabledRef.current = false;
      setEnabled(enabledRef.current);
    } else {
      timer.current = setInterval(tick, interval);
      enabledRef.current = true;
      setEnabled(enabledRef.current);
    }
  }

  const onUnmount = useEffectEvent(() => {
    clearInterval(timer.current);
  });
  useEffect(() => () => onUnmount(), []);

  return (
    <section
      className={cx("auto-refresh", className)}
      aria-label="Auto-refresh"
      style={style}
      {...scopeAttributes(attributes)}
    >
      <button type="button" aria-pressed={enabled} onClick={toggle}>
        Auto-refresh
      </button>
      <p role="status">{enabled ? "Refreshing" : "Paused"}</p>
    </section>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#vue

<!-- prettier-ignore -->
```vue [AutoRefresh.vue]
<script setup lang="ts">
import { onUnmounted, ref } from "vue";

export interface AutoRefreshProps {
  /** Milliseconds between two refreshes. */
  interval: number;
}

const { interval } = defineProps<AutoRefreshProps>();
const emit = defineEmits<{ refresh: [count: number] }>();

const enabled = ref(false);
let timer: ReturnType<typeof setInterval> | undefined;
let refreshes = 0;

function tick() {
  refreshes += 1;
  emit("refresh", refreshes);
}

function toggle() {
  if (enabled.value) {
    clearInterval(timer);
    enabled.value = false;
  } else {
    timer = setInterval(tick, interval);
    enabled.value = true;
  }
}

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<template>
  <section class="auto-refresh" aria-label="Auto-refresh">
    <button type="button" :aria-pressed="enabled" @click="toggle">Auto-refresh</button>
    <p role="status">{{ enabled ? "Refreshing" : "Paused" }}</p>
  </section>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [AutoRefresh.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts" module>
  export interface AutoRefreshProps {
    /** Milliseconds between two refreshes. */
    interval: number;
  }
</script>

<script lang="ts">
  import { onMount } from "svelte";
  import type { ClassValue } from "svelte/elements";

  type Props = AutoRefreshProps & {
    onrefresh?: (count: number) => void;
    class?: ClassValue;
    style?: string;
  };

  let { interval, onrefresh, class: className, style, ...attributes }: Props = $props();

  let enabled = $state(false);
  let timer: ReturnType<typeof setInterval> | undefined;
  let refreshes = 0;

  function tick() {
    refreshes += 1;
    onrefresh?.(refreshes);
  }

  function toggle() {
    if (enabled) {
      clearInterval(timer);
      enabled = false;
    } else {
      timer = setInterval(tick, interval);
      enabled = true;
    }
  }

  onMount(() => () => {
    clearInterval(timer);
  });

  /** The scope attributes of the styled parents that render this component, for its root. */
  function scopeAttributes(props: object): Record<string, ""> {
    const scope: Record<string, ""> = {};
    for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
    return scope;
  }
</script>

<section
  class={["auto-refresh", className]}
  aria-label="Auto-refresh"
  {style}
  {...scopeAttributes(attributes)}
>
  <button type="button" aria-pressed={enabled} onclick={toggle}>Auto-refresh</button
  ><p role="status">{enabled ? "Refreshing" : "Paused"}</p>
</section>
```

#angular

<!-- prettier-ignore -->
```ts [auto-refresh.ts]
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input,
  output,
  signal,
} from "@angular/core";

export interface AutoRefreshProps {
  /** Milliseconds between two refreshes. */
  interval: number;
}

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

@Component({
  selector: "uf-auto-refresh",
  imports: [ScopeAttributes],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let enabled = this.enabled();
    <section
      class="auto-refresh"
      aria-label="Auto-refresh"
      [class]="this.class()"
      [style]="this.style()"
      [ufScope]="this.host"
    >
      <button type="button" [attr.aria-pressed]="enabled" (click)="toggle()">Auto-refresh</button>
      <p role="status">{{ enabled ? "Refreshing" : "Paused" }}</p>
    </section>
  `,
})
export default class AutoRefresh implements OnDestroy {
  readonly interval = input.required<number>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly refresh = output<number>();
  private readonly platformId = inject(PLATFORM_ID);
  private readonly tick = () => {
    this.refreshes += 1;
    this.refresh.emit(this.refreshes);
  };
  protected readonly enabled = signal(false);
  private timer: ReturnType<typeof setInterval> | undefined;
  private refreshes = 0;

  ngOnDestroy(): void {
    if (isPlatformBrowser(this.platformId)) {
      clearInterval(this.timer);
    }
  }

  protected toggle() {
    if (this.enabled()) {
      clearInterval(this.timer);
      this.enabled.set(false);
    } else {
      this.timer = setInterval(this.tick, this.interval());
      this.enabled.set(true);
    }
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [AutoRefresh.tsx]
import { type JSX, createSignal, onCleanup, onMount } from "solid-js";

export interface AutoRefreshProps {
  /** Milliseconds between two refreshes. */
  interval: number;
}

export interface AutoRefreshEvents {
  onRefresh?: (count: number) => void;
}

export default function AutoRefresh(
  props: AutoRefreshProps & AutoRefreshEvents & { class?: string; style?: JSX.CSSProperties },
) {
  const [enabled, setEnabled] = createSignal(false);
  let timer: ReturnType<typeof setInterval> | undefined;
  let refreshes = 0;

  function tick() {
    refreshes += 1;
    props.onRefresh?.(refreshes);
  }

  function toggle() {
    if (enabled()) {
      clearInterval(timer);
      setEnabled(false);
    } else {
      timer = setInterval(tick, props.interval);
      setEnabled(true);
    }
  }

  onMount(() =>
    onCleanup(() => {
      clearInterval(timer);
    }),
  );

  return (
    <section
      class={props.class ? `auto-refresh ${props.class}` : "auto-refresh"}
      aria-label="Auto-refresh"
      style={props.style}
      {...scopeAttributes(props)}
    >
      <button type="button" aria-pressed={enabled()} onClick={toggle}>
        Auto-refresh
      </button>
      <p role="status">{enabled() ? "Refreshing" : "Paused"}</p>
    </section>
  );
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
```

#qwik

<!-- prettier-ignore -->
```tsx [AutoRefresh.tsx]
import {
  $,
  type CSSProperties,
  type ClassList,
  type QRL,
  component$,
  useSignal,
  useVisibleTask$,
} from "@qwik.dev/core";

export interface AutoRefreshProps {
  /** Milliseconds between two refreshes. */
  interval: number;
}

export interface AutoRefreshEvents {
  onRefresh$?: QRL<(count: number) => void>;
}

export default component$<
  AutoRefreshProps & AutoRefreshEvents & { class?: ClassList; style?: CSSProperties }
>(({ interval, onRefresh$, class: className, style, ...attributes }) => {
  const enabled = useSignal(false);
  const timer = useSignal<ReturnType<typeof setInterval> | undefined>();
  const refreshes = useSignal(0);

  const tick = $(() => {
    refreshes.value += 1;
    onRefresh$?.(refreshes.value);
  });

  const toggle = $(() => {
    if (enabled.value) {
      clearInterval(timer.value);
      enabled.value = false;
    } else {
      timer.value = setInterval(tick, interval);
      enabled.value = true;
    }
  });

  useVisibleTask$(
    ({ cleanup }) => {
      cleanup(() => {
        clearInterval(timer.value);
      });
    },
    { strategy: "document-ready" },
  );

  return (
    <section
      class={["auto-refresh", className]}
      aria-label="Auto-refresh"
      {...scopeAttributes(attributes)}
      style={style}
    >
      <button type="button" aria-pressed={enabled.value} onClick$={toggle}>
        Auto-refresh
      </button>
      <p role="status">{enabled.value ? "Refreshing" : "Paused"}</p>
    </section>
  );
});

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#astro

<!-- prettier-ignore -->
```astro [AutoRefresh.astro]
---
export interface AutoRefreshProps {
  /** Milliseconds between two refreshes. */
  interval: number;
}

interface Props extends AutoRefreshProps {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { class: className, style } = Astro.props;

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}

const enabled = false as boolean;
---

<section
  class:list={["auto-refresh", className]}
  aria-label="Auto-refresh"
  style={style}
  {...scopeAttributes(Astro.props)}
>
  <button type="button" aria-pressed={enabled}>Auto-refresh</button>
  <p role="status">{enabled ? "Refreshing" : "Paused"}</p>
</section>
```

::

- React writes an effect whose cleanup runs the callback, declared after every other effect.
- Vue writes `onUnmounted`.
- Svelte writes `onMount` with a function it returns, never `onDestroy`, which Svelte's server runs too, and prints a hook declared before a watcher with a cleanup after it.
- Angular writes `ngOnDestroy`, under a check that the platform is the browser: Angular destroys a component on the server after it renders.
- Solid writes `onMount(() => onCleanup(…))`: a plain `onCleanup` would also run when Solid's server disposes its render. Solid disposes in the reverse of creation, so the hooks come before the first watcher, in reverse order.
- Qwik writes the cleanup of a visible task, registered after every other task.
- Astro drops the hook.

The timer's callback runs later, after renders that may have passed new props. So React reads the props and listeners that deferred code uses through mirror refs, such as `onRefreshRef`, synced after every render. Angular makes `tick` an arrow function field, which keeps its `this` when `setInterval` calls it, declared before the setup's state and `let`s, whose initial values could call it. `timer` and `refreshes` are setup `let`s: a `useRef` on React, a field on Angular, a signal on Qwik ([State](/docs/components/state#setup-lets)).

When the component is removed, every watcher's and `watchEffect`'s cleanup runs before the `onUnmounted` hooks, on every target ([Semantics](/docs/reference/semantics#teardown)). Teardown code reads no template ref, and does not wait ([UF2026](/docs/reference/diagnostics#UF2026)): Vue empties a template ref before `onUnmounted` runs, and React before an effect's cleanup runs, where Svelte, Angular and Qwik still hold the element; and Vue drops an emit once the component is unmounted. Read the element in the callback that sets up the work, and keep it in a local or a setup `let`.

### Listening to the document

A component listens to the document or the window from `onMounted`, and stops in `onUnmounted`. A listener that reads a template ref reads it when its event fires, while the component is mounted, so removing it reads nothing:

<!-- prettier-ignore -->
```tsx [ProfileMenu.uf.tsx]
function onDocumentClick(event: MouseEvent) {
  const element = menu.value;
  if (open.value && element && !element.contains(event.target as Node)) {
    open.value = false;
    emit("closed");
  }
}

onMounted(() => {
  document.addEventListener("click", onDocumentClick);
});

onUnmounted(() => {
  document.removeEventListener("click", onDocumentClick);
});
```

The listener that `onUnmounted` removes must be the one `onMounted` added. React declares it once for the instance's life, so it reads state and props through the mirrors:

<!-- prettier-ignore -->
```tsx [ProfileMenu.tsx]
const [onDocumentClick] = useState(() => (event: MouseEvent) => {
  const element = menu.current;
  if (openRef.current && element && !element.contains(event.target as Node)) {
    openRef.current = false;
    setOpen(openRef.current);
    onClosedRef.current?.();
  }
});

const onMount = useEffectEvent(() => {
  document.addEventListener("click", onDocumentClick);
});
useEffect(() => {
  onMount();
}, []);

const onUnmount = useEffectEvent(() => {
  document.removeEventListener("click", onDocumentClick);
});
useEffect(() => () => onUnmount(), []);
```

Qwik creates a component's `$()` functions again each time it renders it, so it holds the listener in a `useConstant`:

<!-- prettier-ignore -->
```tsx [ProfileMenu.tsx]
const onDocumentClick = useConstant(() =>
  $((event: MouseEvent) => {
    const element = menu.value ?? null;
    if (open.value && element && !element.contains(event.target as Node)) {
      open.value = false;
      onClosed$?.();
    }
  }),
);

useVisibleTask$(
  () => {
    document.addEventListener("click", onDocumentClick);
  },
  { strategy: "document-ready" },
);

useVisibleTask$(
  ({ cleanup }) => {
    cleanup(() => {
      document.removeEventListener("click", onDocumentClick);
    });
  },
  { strategy: "document-ready" },
);
```

A `preventDefault()` in a local function that client code adds as a listener runs as the DOM calls it, on every target but Qwik. There a function that reads the component's state is a `$()` function, which runs once its code has loaded, after the event, so its control is `conditional-event-control`, an error ([Events](/docs/components/events#preventing-the-default)). A Ctrl+S shortcut on the document that prevents the browser's save has no Qwik output for that reason.

## nextTick

A write does not reach the DOM at once on every target. In client code, `await nextTick()` waits until the DOM shows the writes made before it:

<!-- prettier-ignore -->
```tsx [ShippingDetails.uf.tsx]
import { defineEmits, nextTick, ref, useTemplateRef } from "@uxfront/unframework";

export default function ShippingDetails() {
  const emit = defineEmits<{ toggled: [items: number] }>();

  const open = ref(false);
  const details = useTemplateRef<HTMLUListElement>();

  async function toggle() {
    open.value = !open.value;
    await nextTick();
    emit("toggled", details.value?.childElementCount ?? 0);
  }

  return (
    <section class="shipping-details" aria-label="Shipping">
      <button type="button" aria-expanded={open.value} onClick={toggle}>
        Shipping details
      </button>
      {open.value && (
        <ul ref={details}>
          <li>Ships in two days</li>
          <li>Free returns</li>
          <li>Tracked delivery</li>
        </ul>
      )}
    </section>
  );
}
```

::framework-switcher
#react

<!-- prettier-ignore -->
```tsx [ShippingDetails.tsx]
import {
  type CSSProperties,
  useEffect,
  useLayoutEffect,
  useReducer,
  useRef,
  useState,
} from "react";

export interface ShippingDetailsEvents {
  onToggled?: (items: number) => void;
}

export interface ShippingDetailsAttributes {
  className?: string;
  style?: CSSProperties;
}

export default function ShippingDetails({
  onToggled,
  className,
  style,
  ...attributes
}: ShippingDetailsEvents & ShippingDetailsAttributes) {
  const onToggledRef = useRef(onToggled);
  useLayoutEffect(() => {
    onToggledRef.current = onToggled;
  });

  const nextTick = useNextTick();
  const [open, setOpen] = useState(false);
  const openRef = useRef(open);
  const details = useRef<HTMLUListElement>(null);

  async function toggle() {
    openRef.current = !openRef.current;
    setOpen(openRef.current);
    await nextTick();
    onToggledRef.current?.(details.current?.childElementCount ?? 0);
  }

  return (
    <section
      className={cx("shipping-details", className)}
      aria-label="Shipping"
      style={style}
      {...scopeAttributes(attributes)}
    >
      <button type="button" aria-expanded={open} onClick={toggle}>
        Shipping details
      </button>
      {open ? (
        <ul ref={details}>
          <li>Ships in two days</li>
          <li>Free returns</li>
          <li>Tracked delivery</li>
        </ul>
      ) : null}
    </section>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}

/**
 * Vue's `nextTick` for one component: the promise resolves once React has rendered the writes
 * made before it and run their effects, and `settled` says nothing they wrote waits to render;
 * in the task of a click or a key that wrote, as on Vue. It resolves when the component unmounts
 * too.
 */
function useNextTick(settled: () => boolean = () => true): () => Promise<void> {
  const pending = useRef<{ ticket: number; resolve: () => void }[]>([]);
  const tickets = useRef(0);
  const mounted = useRef(false);
  const [rendered, render] = useReducer(
    (last: number, ticket: number) => Math.max(last, ticket),
    0,
  );
  useEffect(() => {
    if (!pending.current.length) return;
    // Once every effect of the commit has run.
    queueMicrotask(() => {
      if (!settled()) {
        // What the component's effects wrote has yet to render, and may end where it was, when
        // React commits nothing: a render of its own makes the next look certain.
        tickets.current += 1;
        render(tickets.current);
        return;
      }
      const due = pending.current.filter(({ ticket }) => ticket <= rendered);
      pending.current = pending.current.filter(({ ticket }) => ticket > rendered);
      for (const { resolve } of due) resolve();
    });
  });
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      queueMicrotask(() => {
        if (mounted.current) return;
        const due = pending.current;
        pending.current = [];
        for (const { resolve } of due) resolve();
      });
    };
  }, []);
  return () =>
    new Promise<void>((resolve) => {
      tickets.current += 1;
      const ticket = tickets.current;
      pending.current.push({ ticket, resolve });
      render(ticket);
    });
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#vue

<!-- prettier-ignore -->
```vue [ShippingDetails.vue]
<script setup lang="ts">
import { nextTick, ref, useTemplateRef } from "vue";

const emit = defineEmits<{ toggled: [items: number] }>();

const open = ref(false);
const details = useTemplateRef<HTMLUListElement>("details");

async function toggle() {
  open.value = !open.value;
  await nextTick();
  emit("toggled", details.value?.childElementCount ?? 0);
}
</script>

<template>
  <section class="shipping-details" aria-label="Shipping">
    <button type="button" :aria-expanded="open" @click="toggle">Shipping details</button>
    <ul v-if="open" ref="details">
      <li>Ships in two days</li>
      <li>Free returns</li>
      <li>Tracked delivery</li>
    </ul>
  </section>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [ShippingDetails.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import { tick } from "svelte";
  import type { ClassValue } from "svelte/elements";

  type Props = { ontoggled?: (items: number) => void; class?: ClassValue; style?: string };

  let { ontoggled, class: className, style, ...attributes }: Props = $props();

  let open = $state(false);
  let details = $state<HTMLUListElement | null>(null);

  async function toggle() {
    open = !open;
    await tick();
    ontoggled?.(details?.childElementCount ?? 0);
  }

  /** The scope attributes of the styled parents that render this component, for its root. */
  function scopeAttributes(props: object): Record<string, ""> {
    const scope: Record<string, ""> = {};
    for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
    return scope;
  }
</script>

<section
  class={["shipping-details", className]}
  aria-label="Shipping"
  {style}
  {...scopeAttributes(attributes)}
>
  <button type="button" aria-expanded={open} onclick={toggle}>Shipping details</button
  >{#if open}
    <ul bind:this={details}>
      <li>Ships in two days</li
      ><li>Free returns</li
      ><li>Tracked delivery</li>
    </ul>
  {/if}
</section>
```

#angular

<!-- prettier-ignore -->
```ts [shipping-details.ts]
import {
  ApplicationRef,
  Component,
  Directive,
  ElementRef,
  type OnInit,
  Renderer2,
  inject,
  input,
  output,
  signal,
  viewChild,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

@Component({
  selector: "uf-shipping-details",
  imports: [ScopeAttributes],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let open = this.open();
    <section
      class="shipping-details"
      aria-label="Shipping"
      [class]="this.class()"
      [style]="this.style()"
      [ufScope]="this.host"
    >
      <button type="button" [attr.aria-expanded]="open" (click)="toggle()">Shipping details</button>
      @if (open) {
        <ul #details>
          <li>Ships in two days</li>
          <li>Free returns</li>
          <li>Tracked delivery</li>
        </ul>
      }
    </section>
  `,
})
export default class ShippingDetails {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly toggled = output<number>();
  private readonly details = viewChild<ElementRef<HTMLUListElement>>("details");
  private readonly appRef = inject(ApplicationRef);
  protected readonly open = signal(false);

  protected async toggle() {
    this.open.set(!this.open());
    await this.nextTick();
    this.toggled.emit(this.details()?.nativeElement.childElementCount ?? 0);
  }

  private async nextTick(): Promise<void> {
    await Promise.resolve();
    this.appRef.tick();
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [ShippingDetails.tsx]
import { type JSX, Show, createSignal, onCleanup } from "solid-js";

export interface ShippingDetailsEvents {
  onToggled?: (items: number) => void;
}

export default function ShippingDetails(
  props: ShippingDetailsEvents & { class?: string; style?: JSX.CSSProperties },
) {
  const [open, setOpen] = createSignal(false);
  let details: HTMLUListElement | null = null;

  async function toggle() {
    setOpen(!open());
    await nextTick();
    props.onToggled?.(details?.childElementCount ?? 0);
  }

  return (
    <section
      class={props.class ? `shipping-details ${props.class}` : "shipping-details"}
      aria-label="Shipping"
      style={props.style}
      {...scopeAttributes(props)}
    >
      <button type="button" aria-expanded={open()} onClick={toggle}>
        Shipping details
      </button>
      <Show when={open()}>
        <ul
          ref={(element) => {
            details = element;
            onCleanup(() => {
              details = null;
            });
          }}
        >
          <li>Ships in two days</li>
          <li>Free returns</li>
          <li>Tracked delivery</li>
        </ul>
      </Show>
    </section>
  );
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}

/**
 * Resolves once the DOM has updated and the watchers have run: Solid applies writes as it makes
 * them, and the watchers run in a microtask queued at the first write, before this one.
 */
function nextTick(): Promise<void> {
  return Promise.resolve();
}
```

#qwik

<!-- prettier-ignore -->
```tsx [ShippingDetails.tsx]
import {
  $,
  type CSSProperties,
  type ClassList,
  type QRL,
  component$,
  useSignal,
} from "@qwik.dev/core";

export interface ShippingDetailsEvents {
  onToggled$?: QRL<(items: number) => void>;
}

export default component$<ShippingDetailsEvents & { class?: ClassList; style?: CSSProperties }>(
  ({ onToggled$, class: className, style, ...attributes }) => {
    const open = useSignal(false);
    const details = useSignal<HTMLUListElement>();

    const toggle = $(async () => {
      open.value = !open.value;
      await nextTick();
      onToggled$?.(rendered(details.value)?.childElementCount ?? 0);
    });

    return (
      <section
        class={["shipping-details", className]}
        aria-label="Shipping"
        {...scopeAttributes(attributes)}
        style={style}
      >
        <button type="button" aria-expanded={open.value} onClick$={toggle}>
          Shipping details
        </button>
        {open.value ? (
          <ul ref={details}>
            <li>Ships in two days</li>
            <li>Free returns</li>
            <li>Tracked delivery</li>
          </ul>
        ) : null}
      </section>
    );
  },
);

/**
 * Resolves once Qwik has rendered the writes made before it: Qwik renders them in a microtask,
 * so they are in the DOM by the next task.
 */
function nextTick(): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve));
}

/**
 * The element a template ref holds while it is in the document, else `null`: Qwik keeps a
 * removed element in its ref, where a template ref is empty once its element is gone (ADR-0049).
 */
function rendered<T extends Element>(element: T | undefined): T | null {
  return element?.isConnected ? element : null;
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#astro

<!-- prettier-ignore -->
```astro [ShippingDetails.astro]
---
interface Props {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { class: className, style } = Astro.props;

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}

const open = false as boolean;
---

<section
  class:list={["shipping-details", className]}
  aria-label="Shipping"
  style={style}
  {...scopeAttributes(Astro.props)}
>
  <button type="button" aria-expanded={open}>Shipping details</button>
  {open ? (
    <ul>
      <li>Ships in two days</li>
      <li>Free returns</li>
      <li>Tracked delivery</li>
    </ul>
  ) : null}
</section>
```

::

- Vue imports `nextTick`, and Svelte `tick`.
- React has no `nextTick`, so the file declares a hook, `useNextTick`, that asks for a render of its own and resolves once React has rendered it, run its effects, and rendered what the component's watchers wrote in turn (`next-tick`, emulated). Where those writes end where they were and React would commit nothing, it asks for one more render. It resolves a pending request when the component unmounts too. The component calls it after the states it checks and before every function that awaits it.
- Angular renders a change in a task of its own, so a private `nextTick` method renders the pending change itself in a microtask, `this.appRef.tick()`, and resolves after it (`next-tick`, emulated).
- Solid applies a write to the DOM as it makes it, and runs the watchers in a microtask queued at the first write, so its `nextTick` helper resolves a promise after them (`next-tick`, emulated).
- Qwik renders a write's changes in a microtask, so its `nextTick` helper resolves after the next task (`next-tick`, emulated). Qwik keeps a removed element in its ref, so a template ref in a conditional reads through `rendered`, which gives the element while it is in the document, and `null` once it is gone.
- Astro drops the handler, and `nextTick` with it.

`nextTick` is a function, not a macro: client code calls it anywhere, a handler, a watcher's callback, a hook or a local function they call. The setup runs before any DOM exists, so it does not call `nextTick` ([UF2005](/docs/reference/diagnostics#UF2005)). It is called bare and awaited: `nextTick(callback)`, and `nextTick` passed or held as a value, are [UF2025](/docs/reference/diagnostics#UF2025), with a safe fix that awaits it where the function can become `async`. On Vue, Svelte, Solid and Angular the code after `await nextTick()` runs in the task that wrote, and on React after a click's or a key's handler; elsewhere it may run after the next event ([Semantics](/docs/reference/semantics#outside-the-contract)). An event's `preventDefault()` after `await nextTick()` comes too late ([UF3033](/docs/reference/diagnostics#UF3033)).

## The server render

Watchers, `watchEffect` and lifecycle hooks never change what the server renders. Here `onMounted` writes the state that a watcher turns into the label:

<!-- prettier-ignore -->
```tsx [NetworkBadge.uf.tsx]
import { onMounted, ref, watch } from "@uxfront/unframework";

export default function NetworkBadge() {
  const online = ref<boolean>();
  const label = ref("Checking the connection");

  watch(online, (value) => {
    label.value = value ? "Online" : "Offline";
  });

  onMounted(() => {
    online.value = navigator.onLine;
  });

  return (
    <p class="network-badge" role="status" data-checked={online.value === undefined ? "no" : "yes"}>
      {label.value}
    </p>
  );
}
```

Every target's server render reads "Checking the connection", and the browser then shows "Online" or "Offline". Vue runs an immediate watcher's first callback during the setup, on the server too, so that callback is held to what the server can run ([UF2013](/docs/reference/diagnostics#UF2013), see [Effects](/docs/components/effects#immediate-watchers-and-cleanup)). Every other effect and every hook runs in the browser only, on every target ([Semantics](/docs/reference/semantics#effects-are-client-only)).

## Not yet

- Whether a parent's hooks run before or after its children's is outside the contract ([Semantics](/docs/reference/semantics#outside-the-contract)).
- Vue's other hooks, such as `onBeforeMount` and `onUpdated`, are not part of the language ([UF2016](/docs/reference/diagnostics#UF2016)): watch the values that change instead.
- An `async` setup lands in M8.

The decision behind this page is [ADR-0048](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0048-effects-and-lifecycle.md).
