[]previous and next page

useImperativeHandle

Publishes an imperative handle to a ref: create() runs once, untracked, and its result is passed to ref; when the owner is disposed ref receives undefined.

Publishes an imperative handle to a ref: create() runs once, untracked, and its result is passed to ref; when the owner is disposed ref receives undefined. Components run once, so the handle never needs refreshing: put live state behind accessors inside the handle.

A missing ref is accepted and create does not run, so forwarding an optional ref needs no branch.

Import#

ts
import { useImperativeHandle } from "@shadow-js/core";

Signature#

ts
function useImperativeHandle<T>(
  ref: ((value: T | undefined) => void) | null | undefined,
  create: () => T,
): void

Parameters#

Name Description
ref The ref callback (a Ref, or any function of the handle). null or undefined makes the call a no-op.
create Builds the handle. Runs once, untracked.

Examples#

ts
import { createRef, useImperativeHandle } from "@shadow-js/core";

function FancyInput(props: { ref?: (handle: { focus(): void } | undefined) => void }) {
  const input = createRef<HTMLInputElement>();
  useImperativeHandle(props.ref, () => ({ focus: () => input.current?.focus() }));
  return <input ref={input} />;
}