useRef$
An observable element ref hook that serves as a drop-in replacement for useRef. Works with callback ref composition and forwardRef patterns. The element is wrapped with opaqueObject to prevent legendapp/state from deeply observing DOM properties.
Standalone (useRef replacement)
Section titled “Standalone (useRef replacement)”import { import useRef$
useRef$ } from "@usels/web";
function function Component(): JSX.Element
Component() { const const el$: any
el$ = import useRef$
useRef$<interface HTMLDivElement
HTMLDivElement>(); return <JSX.IntrinsicElements.div: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div RefAttributes<HTMLDivElement>.ref?: Ref<HTMLDivElement> | undefined
Allows getting a ref to the component instance.
Once the component unmounts, React will set ref.current to null
(or call the ref with null if you passed a callback ref).
ref={const el$: any
el$} />;}import { createRef$ } from "@usels/web";
function Component() { "use scope" const el$ = createRef$<HTMLDivElement>(); return <div ref={el$} />;}Reactive access with observe
Section titled “Reactive access with observe”Calling el$.get() inside observe automatically re-runs the observer when the element is mounted or unmounted.
import { useObserve, useRef$ } from "@usels/web";
function Component() { const el$ = useRef$<HTMLDivElement>();
useObserve(() => { const el = el$.get(); if (el) el.focus(); });
return <div ref={el$} />;}import { createRef$ } from "@usels/web";
function Component() { "use scope" const el$ = createRef$<HTMLDivElement>();
observe(() => { const el = el$.get(); if (el) el.focus(); });
return <div ref={el$} />;}forwardRef pattern
Section titled “forwardRef pattern”import { forwardRef } from "react";import { useRef$ } from "@usels/web";
const Component = forwardRef<HTMLDivElement>((props, ref) => { const el$ = useRef$(ref);
useObserve(() => { const el = el$.get(); if (el) { console.log("element mounted:", el); } });
return <div ref={el$} />;});