UNPKG

@wordpress/compose

Version:
8 lines (7 loc) 2.01 kB
{ "version": 3, "sources": ["../../../src/hooks/use-ref-effect/index.ts"], "sourcesContent": ["/**\n * External dependencies\n */\nimport type { DependencyList, RefCallback } from 'react';\n\n/**\n * WordPress dependencies\n */\nimport { useCallback, useRef } from '@wordpress/element';\n\n/**\n * Effect-like ref callback. Just like with `useEffect`, this allows you to\n * return a cleanup function to be run if the ref changes or one of the\n * dependencies changes. The ref is provided as an argument to the callback\n * functions. The main difference between this and `useEffect` is that\n * the `useEffect` callback is not called when the ref changes, but this is.\n * Pass the returned ref callback as the component's ref and merge multiple refs\n * with `useMergeRefs`.\n *\n * It's worth noting that if the dependencies array is empty, there's not\n * strictly a need to clean up event handlers for example, because the node is\n * to be removed. It *is* necessary if you add dependencies because the ref\n * callback will be called multiple times for the same node.\n *\n * @param callback Callback with ref as argument.\n * @param dependencies Dependencies of the callback.\n *\n * @return Ref callback.\n */\nexport default function useRefEffect< TElement = Node >(\n\tcallback: ( node: TElement ) => ( () => void ) | void,\n\tdependencies: DependencyList\n): RefCallback< TElement | null > {\n\tconst cleanupRef = useRef< ( () => void ) | void >( undefined );\n\treturn useCallback( ( node: TElement | null ) => {\n\t\tif ( node ) {\n\t\t\tcleanupRef.current = callback( node );\n\t\t} else if ( cleanupRef.current ) {\n\t\t\tcleanupRef.current();\n\t\t}\n\t}, dependencies );\n}\n"], "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,qBAAoC;AAqBrB,SAAR,aACN,UACA,cACiC;AACjC,QAAM,iBAAa,uBAAiC,MAAU;AAC9D,aAAO,4BAAa,CAAE,SAA2B;AAChD,QAAK,MAAO;AACX,iBAAW,UAAU,SAAU,IAAK;AAAA,IACrC,WAAY,WAAW,SAAU;AAChC,iBAAW,QAAQ;AAAA,IACpB;AAAA,EACD,GAAG,YAAa;AACjB;", "names": [] }