Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Compose: Fix 'useFocusOnMount' cleanup callback
  • Loading branch information
Mamaduka committed May 28, 2024
commit 9c4ed86d293faa6547ea12a6481f6a2f37c90973
23 changes: 13 additions & 10 deletions packages/compose/src/hooks/use-focus-on-mount/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
/**
* WordPress dependencies
*/
import { useRef, useEffect, useCallback } from '@wordpress/element';
import { useRef, useEffect } from '@wordpress/element';
import { focus } from '@wordpress/dom';

/**
* Internal dependencies
*/
import useRefEffect from '../use-ref-effect';

/**
* Hook used to focus the first tabbable element on mount.
*
Expand Down Expand Up @@ -50,15 +55,7 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) {
focusOnMountRef.current = focusOnMount;
}, [ focusOnMount ] );

useEffect( () => {
return () => {
if ( timerId.current ) {
clearTimeout( timerId.current );
}
};
}, [] );

return useCallback( ( node ) => {
return useRefEffect( ( node ) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice use of useRefEffect 👍

if ( ! node || focusOnMountRef.current === false ) {
return;
}
Expand All @@ -80,5 +77,11 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) {
}

setFocus( node );

return () => {
if ( timerId.current ) {
clearTimeout( timerId.current );
}
};
}, [] );
}