Skip to content

Commit f7b4229

Browse files
jsnajdrtalldanciampoellatrix
authored
useBlockElement: return null until ref callback has time to clean up the old element (#63565)
Unlinked contributors: sergiu-radu. Co-authored-by: jsnajdr <[email protected]> Co-authored-by: talldan <[email protected]> Co-authored-by: ciampo <[email protected]> Co-authored-by: ellatrix <[email protected]>
1 parent 121accc commit f7b4229

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

packages/block-editor/src/components/block-list/use-block-props/use-block-refs.js

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
/**
22
* WordPress dependencies
33
*/
4-
import { useContext, useMemo, useRef } from '@wordpress/element';
5-
import { useRefEffect, useObservableValue } from '@wordpress/compose';
4+
import {
5+
useContext,
6+
useMemo,
7+
useRef,
8+
useState,
9+
useLayoutEffect,
10+
} from '@wordpress/element';
11+
import { useRefEffect } from '@wordpress/compose';
612

713
/**
814
* Internal dependencies
@@ -67,7 +73,17 @@ function useBlockRef( clientId ) {
6773
*/
6874
function useBlockElement( clientId ) {
6975
const { refsMap } = useContext( BlockRefs );
70-
return useObservableValue( refsMap, clientId ) ?? null;
76+
const [ blockElement, setBlockElement ] = useState( null );
77+
// Delay setting the resulting `blockElement` until an effect. If the block element
78+
// changes (i.e., the block is unmounted and re-mounted), this allows enough time
79+
// for the ref callbacks to clean up the old element and set the new one.
80+
useLayoutEffect( () => {
81+
setBlockElement( refsMap.get( clientId ) );
82+
return refsMap.subscribe( clientId, () =>
83+
setBlockElement( refsMap.get( clientId ) )
84+
);
85+
}, [ refsMap, clientId ] );
86+
return blockElement;
7187
}
7288

7389
export { useBlockRef as __unstableUseBlockRef };

0 commit comments

Comments
 (0)