UNPKG

@storm-stack/hooks

Version:

A collection of React hooks used by Storm Software in various client libraries and applications.

19 lines (18 loc) 638 B
import * as React from "react"; import { useIsomorphicLayoutEffect } from "./use-isomorphic-layout-effect.mjs"; export function useEvent(callback) { return useGet(callback, defaultValue, true); } const defaultValue = () => { throw new Error("Cannot call an event handler while rendering."); }; function useGet(currentValue, initialValue, forwardToFunction) { const curRef = React.useRef(initialValue ?? currentValue); useIsomorphicLayoutEffect(() => { curRef.current = currentValue; }); return React.useCallback( forwardToFunction ? (...args) => curRef.current?.apply(null, args) : () => curRef.current, [] ); }