import type { ReactNode } from 'react'; import { createContext, useContext, useMemo } from 'react'; export function createNestableContext(defaultValue: T) { const context = createContext>(new Map()); function useNestedContext(id?: string): T { const values = useContext(context); if (values.has(id)) { return values.get(id) as T; } return defaultValue; } function NestedContextProvider(props: { id?: string; value: T; children: ReactNode; }) { const { id, value, children } = props; const parentValues = useContext(context); const mergedValues = useMemo(() => { const merged = new Map(parentValues); merged.set(id, value); return merged; }, [parentValues, id, value]); return {children}; } return { useNestedContext, NestedContextProvider, }; }