Skip to content

Commit bc43d19

Browse files
committed
Refactor update on block move to a different effect to reduce event binding
1 parent 6f2e887 commit bc43d19

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

packages/block-editor/src/components/block-tools/use-block-toolbar-popover-props.js

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
*/
44
import { useRefEffect } from '@wordpress/compose';
55
import { useSelect } from '@wordpress/data';
6-
import { useEffect, useState } from '@wordpress/element';
6+
import { useCallback, useEffect, useState } from '@wordpress/element';
77

88
/**
99
* Internal dependencies
@@ -76,18 +76,24 @@ export default function useBlockToolbarPopoverProps( {
7676
setToolbarHeight( popoverNode.offsetHeight );
7777
}, [] );
7878

79+
const updateProps = useCallback(
80+
() =>
81+
setProps(
82+
getProps( contentElement, selectedBlockElement, toolbarHeight )
83+
),
84+
[ contentElement, selectedBlockElement, toolbarHeight ]
85+
);
86+
87+
// Update props when the block is moved. This also ensures the props are
88+
// correct on initial mount.
89+
useEffect( updateProps, [ blockIndex ] );
90+
91+
// Update props when the viewport is resized or the block is resized.
7992
useEffect( () => {
8093
if ( ! contentElement || ! selectedBlockElement ) {
8194
return;
8295
}
8396

84-
const updateProps = () =>
85-
setProps(
86-
getProps( contentElement, selectedBlockElement, toolbarHeight )
87-
);
88-
89-
updateProps();
90-
9197
// Update the toolbar props on viewport resize.
9298
const contentView = contentElement?.ownerDocument?.defaultView;
9399
contentView?.addEventHandler?.( 'resize', updateProps );
@@ -107,12 +113,7 @@ export default function useBlockToolbarPopoverProps( {
107113
resizeObserver.disconnect();
108114
}
109115
};
110-
111-
// The deps will update the toolbar props if:
112-
// - The content or the selected block element changes.
113-
// - The block is moved (its index changes).
114-
// - The height of the toolbar changes.
115-
}, [ contentElement, selectedBlockElement, blockIndex, toolbarHeight ] );
116+
}, [ updateProps, contentElement, selectedBlockElement ] );
116117

117118
return {
118119
...props,

0 commit comments

Comments
 (0)