Skip to content

useLazyRef

Hook that works 'partially' like the useState hook with lazy initialization: ensures that the initializer function is executed only once.

Demo

INFO

There are two functions initializer and initializerLazy that log a message when they runs then sum and return number from 0 to 100.

The component has:

  • a lazyValue creates by useLazyRef hook with initializerLazy function as param.
  • a value creates by useRef hook with initializer function executed as param.
  • a rerender function created by useRerender hook to force a rerender.
  • a apply function created by useInterval hook to execute rerender function every second.
  • render a div with lazyValue and value values.

If you open devtools will see that initializerLazy message is logged once while initializer message every rerender.

Loading demo…
Show source code
tsx
import { useRef } from "react";
import { useInterval, useLazyRef, useRerender } from "../../../..";

const initializer = () => {
	console.log("initializer run...")
	return Array(100).fill(true).reduce((prev, _, index) => prev + index, 0);
}

const initializerLazy = () => {
	console.log("initializerLazy run...")
	return Array(100).fill(true).reduce((prev, _, index) => prev + index, 0);
}

export const UseLazyRef = () => {
	const rerender = useRerender();
	const [apply] = useInterval(() => rerender(), 1000);
	const lazyValue = useLazyRef(initializerLazy);
	const value = useRef(initializer());

	apply();

	return (
		<div>
			<p>Value is: {value.current}</p>
			<p>LazyValue is: {lazyValue.current}</p>
		</div>
	);
}

Types

UseLazyRefProps

  • @template T - The type of the value produced by the initializer and stored in the ref. Inferred automatically from the return type of initializer.

Parameters accepted by useLazyRef.

PropertyTypeRequiredDescription
initializer() => TA factory function invoked exactly once on the first render to produce the initial value stored in the ref. Unlike passing a value directly to useRef, this avoids re-creating expensive objects on every render — the initializer is only called when the ref is first created.

UseLazyRefResult

  • @template T - The type of the value stored in the ref.

Return value of useLazyRef.

A mutable ref object whose .current property is initialised lazily on the first render via initializer and persists for the lifetime of the component. Mutating .current does not trigger a re-render.

ts
export type UseLazyRefResult<T> = React.MutableRefObject<T>;

Released under the MIT License.