Skip to content
Reactivity

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.

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$
} />;
}

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 { 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$} />;
});

View on GitHub