Skip to content

Commit

Permalink
Extract assignRef function outside the hook
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnajdr committed Jul 29, 2024
1 parent aa78bb4 commit 9f4ee9b
Showing 1 changed file with 13 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
/**
* WordPress dependencies
*/
import {
useContext,
useState,
useLayoutEffect,
useCallback,
} from '@wordpress/element';
import { useContext, useState, useLayoutEffect } from '@wordpress/element';
import { useRefEffect } from '@wordpress/compose';

/**
Expand Down Expand Up @@ -35,6 +30,14 @@ export function useBlockRefProvider( clientId ) {
);
}

function assignRef( ref, value ) {
if ( typeof ref === 'function' ) {
ref( value );
} else if ( ref ) {
ref.current = value;
}
}

/**
* Tracks the DOM element for the block identified by `clientId` and assigns it to the `ref`
* whenever it changes.
Expand All @@ -44,27 +47,16 @@ export function useBlockRefProvider( clientId ) {
*/
export function useBlockElementRef( clientId, ref ) {
const { refsMap } = useContext( BlockRefs );
const setRef = useCallback(
( el ) => {
if ( typeof ref === 'function' ) {
ref( el );
} else if ( ref ) {
ref.current = el;
}
},
[ ref ]
);

useLayoutEffect( () => {
setRef( refsMap.get( clientId ) );
assignRef( ref, refsMap.get( clientId ) );
const unsubscribe = refsMap.subscribe( clientId, () =>
setRef( refsMap.get( clientId ) )
assignRef( ref, refsMap.get( clientId ) )
);
return () => {
unsubscribe();
setRef( null );
assignRef( ref, null );
};
}, [ refsMap, clientId, setRef ] );
}, [ refsMap, clientId, ref ] );
}

/**
Expand Down

0 comments on commit 9f4ee9b

Please sign in to comment.