From ae12d948f10378016cf436f8e5890f70072181e6 Mon Sep 17 00:00:00 2001 From: Zebulan Stanphill Date: Wed, 13 Oct 2021 14:43:20 -0500 Subject: [PATCH] Convert usePrevious hook to TypeScript. (#35597) --- .../compose/src/hooks/use-previous/index.js | 31 ------------------- .../compose/src/hooks/use-previous/index.ts | 24 ++++++++++++++ 2 files changed, 24 insertions(+), 31 deletions(-) delete mode 100644 packages/compose/src/hooks/use-previous/index.js create mode 100644 packages/compose/src/hooks/use-previous/index.ts diff --git a/packages/compose/src/hooks/use-previous/index.js b/packages/compose/src/hooks/use-previous/index.js deleted file mode 100644 index c50e392a43226..0000000000000 --- a/packages/compose/src/hooks/use-previous/index.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * WordPress dependencies - */ -import { useEffect, useRef } from '@wordpress/element'; - -/** - * Use something's value from the previous render. - * Based on https://usehooks.com/usePrevious/. - * - * @template T - * - * @param {T} value The value to track. - * - * @return {T | undefined} The value from the previous render. - */ -export default function usePrevious( value ) { - // Disable reason: without an explicit type detail, the type of ref will be - // inferred based on the initial useRef argument, which is undefined. - // https://github.com/WordPress/gutenberg/pull/22597#issuecomment-633588366 - /* eslint-disable jsdoc/no-undefined-types */ - const ref = useRef( /** @type {T | undefined} */ ( undefined ) ); - /* eslint-enable jsdoc/no-undefined-types */ - - // Store current value in ref. - useEffect( () => { - ref.current = value; - }, [ value ] ); // Re-run when value changes. - - // Return previous value (happens before update in useEffect above). - return ref.current; -} diff --git a/packages/compose/src/hooks/use-previous/index.ts b/packages/compose/src/hooks/use-previous/index.ts new file mode 100644 index 0000000000000..cdc06c37f08fe --- /dev/null +++ b/packages/compose/src/hooks/use-previous/index.ts @@ -0,0 +1,24 @@ +/** + * WordPress dependencies + */ +import { useEffect, useRef } from '@wordpress/element'; + +/** + * Use something's value from the previous render. + * Based on https://usehooks.com/usePrevious/. + * + * @param value The value to track. + * + * @return The value from the previous render. + */ +export default function usePrevious< T >( value: T ): T | undefined { + const ref = useRef< T >(); + + // Store current value in ref. + useEffect( () => { + ref.current = value; + }, [ value ] ); // Re-run when value changes. + + // Return previous value (happens before update in useEffect above). + return ref.current; +}