UNPKG

1.28 kBJavaScriptView Raw
1import equal from 'fast-deep-equal';
2import { useCallback, useState } from 'react';
3import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect.js';
4/**
5 *
6 * @param monitor The monitor to collect state from
7 * @param collect The collecting function
8 * @param onUpdate A method to invoke when updates occur
9 */ export function useCollector(monitor, collect, onUpdate) {
10 const [collected, setCollected] = useState(()=>collect(monitor)
11 );
12 const updateCollected = useCallback(()=>{
13 const nextValue = collect(monitor);
14 // This needs to be a deep-equality check because some monitor-collected values
15 // include XYCoord objects that may be equivalent, but do not have instance equality.
16 if (!equal(collected, nextValue)) {
17 setCollected(nextValue);
18 if (onUpdate) {
19 onUpdate();
20 }
21 }
22 }, [
23 collected,
24 monitor,
25 onUpdate
26 ]);
27 // update the collected properties after react renders.
28 // Note that the "Dustbin Stress Test" fails if this is not
29 // done when the component updates
30 useIsomorphicLayoutEffect(updateCollected);
31 return [
32 collected,
33 updateCollected
34 ];
35}
36
37//# sourceMappingURL=useCollector.js.map
\No newline at end of file