@wordpress/compose
Version:
WordPress higher-order components (HOCs).
8 lines (7 loc) • 1.77 kB
Source Map (JSON)
{
"version": 3,
"sources": ["../../../src/hooks/use-event/index.ts"],
"sourcesContent": ["/**\n * WordPress dependencies\n */\nimport { useRef, useInsertionEffect, useCallback } from '@wordpress/element';\n\n/**\n * Any function.\n */\nexport type AnyFunction = ( ...args: any ) => any;\n\n/**\n * Creates a stable callback function that has access to the latest state and\n * can be used within event handlers and effect callbacks. Throws when used in\n * the render phase.\n *\n * @param callback The callback function to wrap.\n *\n * @example\n *\n * ```tsx\n * function Component( props ) {\n * const onClick = useEvent( props.onClick );\n * useEffect( () => {\n * onClick();\n * // Won't trigger the effect again when props.onClick is updated.\n * }, [ onClick ] );\n * // Won't re-render Button when props.onClick is updated (if `Button` is\n * // wrapped in `React.memo`).\n * return <Button onClick={ onClick } />;\n * }\n * ```\n */\nexport default function useEvent< T extends AnyFunction >(\n\t/**\n\t * The callback function to wrap.\n\t */\n\tcallback?: T\n) {\n\tconst ref = useRef< AnyFunction | undefined >( () => {\n\t\tthrow new Error(\n\t\t\t'Callbacks created with `useEvent` cannot be called during rendering.'\n\t\t);\n\t} );\n\tuseInsertionEffect( () => {\n\t\tref.current = callback;\n\t} );\n\treturn useCallback< AnyFunction >(\n\t\t( ...args ) => ref.current?.( ...args ),\n\t\t[]\n\t) as T;\n}\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,qBAAwD;AA6BzC,SAAR,SAIN,UACC;AACD,QAAM,UAAM,uBAAmC,MAAM;AACpD,UAAM,IAAI;AAAA,MACT;AAAA,IACD;AAAA,EACD,CAAE;AACF,yCAAoB,MAAM;AACzB,QAAI,UAAU;AAAA,EACf,CAAE;AACF,aAAO;AAAA,IACN,IAAK,SAAU,IAAI,UAAW,GAAG,IAAK;AAAA,IACtC,CAAC;AAAA,EACF;AACD;",
"names": []
}