import { useEffect , useState } from 'react' ; import useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect' ; let serverHandoffComplete = false ; const registry = new Map ( ) ; const genId = ( prefix ) => { if ( registry . has ( prefix ) ) { const val = registry . get ( prefix ) ; const update = val ? val + 1 : 1 ; registry . set ( prefix , update ) ; return update ; } else { registry . set ( prefix , 1 ) ; return 1 ; } } ; param options { prefix param options . prefix param options . id function useIdAllocator ( { prefix , id : idProp , } ) { const initialId = prefix && ( serverHandoffComplete ? genId ( prefix ) : null ) ; const [ id , setId ] = useState ( initialId ) ; useIsomorphicLayoutEffect ( ( ) => { if ( prefix && id === null ) { setId ( genId ( prefix ) ) ; } } , [ ] ) ; useEffect ( ( ) => { if ( serverHandoffComplete === false ) { serverHandoffComplete = true ; } } , [ ] ) ; return idProp ? idProp : `${ prefix }-${ id }` ; } export default useIdAllocator ;