Skip to content
Closed
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
31 changes: 27 additions & 4 deletions packages/data/src/components/use-select/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ const useIsomorphicLayoutEffect =

const renderQueue = createQueue();

// Arbitrarily picked low number
const THROTTLE_MS = 10;

/**
* Custom react hook for retrieving props from registered selectors.
*
Expand Down Expand Up @@ -136,6 +139,7 @@ export default function useSelect( _mapSelect, deps ) {
}
} );

const throttleRef = useRef( null );
useIsomorphicLayoutEffect( () => {
const onStoreChange = () => {
if ( isMountedAndNotUnsubscribing.current ) {
Expand All @@ -157,23 +161,42 @@ export default function useSelect( _mapSelect, deps ) {
}
};

// A single dispatch() call may cause multiple store changes in a very brief
// period of time. There is little value in recomputing selector in response
// to every atomic update. Throttling ensures this doesn't happen more often
// than once in THROTTLE_MS milliseconds.
const throttledOnStoreChange = () => {
if ( throttleRef.current ) {
return;
}
throttleRef.current = setTimeout( () => {
throttleRef.current = null;
onStoreChange();
}, THROTTLE_MS );
};

// catch any possible state changes during mount before the subscription
// could be set.
if ( latestIsAsync.current ) {
renderQueue.add( queueContext, onStoreChange );
renderQueue.add( queueContext, throttledOnStoreChange );
} else {
onStoreChange();
throttledOnStoreChange();
}

const unsubscribe = registry.subscribe( () => {
if ( latestIsAsync.current ) {
renderQueue.add( queueContext, onStoreChange );
renderQueue.add( queueContext, throttledOnStoreChange );
} else {
onStoreChange();
throttledOnStoreChange();
}
} );

return () => {
if ( throttleRef.current ) {
clearTimeout( throttleRef.current );
throttleRef.current = null;
onStoreChange();
}
isMountedAndNotUnsubscribing.current = false;
unsubscribe();
renderQueue.flush( queueContext );
Expand Down