import React from 'react' import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector' import type { GridState } from '../../state' import { GridContext } from './context' import type { GridRowId, GridRowMeta } from '../../types' export const useGridContext = () => React.useContext(GridContext) export const useGridApi = () => { const grid = useGridContext() return grid.api } /** * This hook will only trigger an element re-render * when both the internal grid store has updated * and the value returned from the passed selector * is different than the previous value */ export const useGridSelector = ( callback: (selector: GridState) => Selection ) => { const store = useGridContext() const res = useSyncExternalStoreWithSelector( store.subscribe, store.getState, undefined, callback ) return res } /** * @internal: this hook is for internal use and might be subject to change */ export const useGridColumn = (columnId: string) => { const { selectors } = useGridContext() return useGridSelector((state) => selectors.selectColumn(state, columnId)) } export const useGridRow = (rowId: GridRowId) => { const { selectors } = useGridContext() const row = useGridSelector((state) => selectors.selectRow(state, rowId)) return row as T } export const useGridRowMeta = ( rowId: GridRowId ) => { const { selectors } = useGridContext() const meta = useGridSelector((state) => selectors.selectRowMeta(state, rowId) ) return meta as T }