Skip to content

Commit

Permalink
useBlockElement: return null until ref callback has time to clean up …
Browse files Browse the repository at this point in the history
…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]>
  • Loading branch information
5 people authored and gutenbergplugin committed Jul 18, 2024
1 parent 9c34196 commit e207359
Showing 1 changed file with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
/**
* WordPress dependencies
*/
import { useContext, useMemo, useRef } from '@wordpress/element';
import { useRefEffect, useObservableValue } from '@wordpress/compose';
import {
useContext,
useMemo,
useRef,
useState,
useLayoutEffect,
} from '@wordpress/element';
import { useRefEffect } from '@wordpress/compose';

/**
* Internal dependencies
Expand Down Expand Up @@ -67,7 +73,17 @@ function useBlockRef( clientId ) {
*/
function useBlockElement( clientId ) {
const { refsMap } = useContext( BlockRefs );
return useObservableValue( refsMap, clientId ) ?? null;
const [ blockElement, setBlockElement ] = useState( null );
// Delay setting the resulting `blockElement` until an effect. If the block element
// changes (i.e., the block is unmounted and re-mounted), this allows enough time
// for the ref callbacks to clean up the old element and set the new one.
useLayoutEffect( () => {
setBlockElement( refsMap.get( clientId ) );
return refsMap.subscribe( clientId, () =>
setBlockElement( refsMap.get( clientId ) )
);
}, [ refsMap, clientId ] );
return blockElement;
}

export { useBlockRef as __unstableUseBlockRef };
Expand Down

0 comments on commit e207359

Please sign in to comment.