@gravity-ui/graph
Version:
Modern graph editor component
44 lines (43 loc) • 1.48 kB
JavaScript
import { useEffect, useLayoutEffect, useMemo } from "react";
import isEqual from "lodash/isEqual";
import { usePrevious } from "./usePrevious";
/**
* Hook for managing graph layers.
*
* Provides a convenient way to add and manage layers in the graph.
* Automatically handles layer initialization and props updates.
* Uses deep props comparison to optimize re-renders.
*
* @example
* ```tsx
* const devToolsLayer = useLayer(graph, DevToolsLayer, {
* showRuler: true,
* rulerSize: 20,
* });
* ```
*
* @template T - Type of layer constructor extending Layer
* @param graph - Graph instance
* @param layerCtor - Layer class constructor
* @param props - Layer properties (excluding internal props like root, camera, graph, emitter)
* @returns Layer instance or null if graph is not initialized
*/
export function useLayer(graph, layerCtor, props) {
const layer = useMemo(() => (graph ? graph.addLayer(layerCtor, props) : null), [graph]);
const prevProps = usePrevious(props);
useLayoutEffect(() => {
// Detach layer on change layer instance
return () => {
// Only detach if both graph and layer are available
if (graph && layer) {
graph.detachLayer(layer);
}
};
}, [graph, layer]);
useEffect(() => {
if (layer && (!prevProps || !isEqual(prevProps, props))) {
layer.setProps(props);
}
}, [layer, props, prevProps]);
return layer;
}