import React, { Dispatch, PropsWithChildren, useCallback, useMemo, } from 'react'; import { useStateRef } from '@leafygreen-ui/hooks'; import { DescendantsProvider } from './DescendantProvider'; import { DescendantsList } from './Descendants.types'; import { DescendantContextType } from './DescendantsContext'; import { descendantsReducer, DescendantsReducerAction, } from './DescendantsReducer'; export interface InitDescendantsReturnObject { /** The descendants list in the current render */ descendants: DescendantsList; /** A setter function for the descendants state */ dispatch: Dispatch>; /** Accessor function for the most up-to-date descendants list */ getDescendants: () => DescendantsList; /** A unique context provider for the given `DescendantsContext` */ Provider: React.ComponentType>; } /** * Initializes a {@link DescendantsList} */ export const useInitDescendants = ( context: DescendantContextType, ): InitDescendantsReturnObject => { // We avoid using `useReducer` here, since we need to internally keep track // of the `descendants`, and provide a means to access the updated list // to avoid accessing a stale descendants list const [descendants, setDescendants, getDescendants] = useStateRef< DescendantsList >([]); const dispatch: Dispatch> = useCallback( action => { const descendants = descendantsReducer(getDescendants(), action); setDescendants(descendants); }, [getDescendants, setDescendants], ); // Create a new Provider for the given context const Provider = useMemo(() => { // eslint-disable-next-line react/display-name return ({ children }: PropsWithChildren<{}>) => { return ( {children} ); }; }, [context, dispatch, getDescendants]); return { descendants, dispatch, getDescendants, Provider, }; };