import { useCallback , useState } from 'react' ; export interface UseCursorProps { pageIndex : number ; pageSize : number ; } type Cursor = string | undefined ; type SetCursor = ( cursor : Cursor ) => void ; type UseCursor = ( props : UseCursorProps ) => [ Cursor , SetCursor ] ; const hash = ( props ) : string => JSON . stringify ( props ) ; export const useCursor = ( { pageIndex , pageSize } ) => { const [ cache , setCache ] = useState < Record < string , Cursor > > ( { } ) ; const setCursor = useCallback < SetCursor > ( ( cursor ) => { setCache ( { ... cache , [ hash ( { pageIndex : pageIndex + 1 , pageSize } ) ] : cursor , } ) ; } , [ pageIndex , pageSize ] ) ; let cursor ; for ( let i = pageIndex ; i >= 0 ; i -- ) { const currentProps = { pageIndex : i , pageSize } ; cursor = cache [ hash ( currentProps ) ] ; if ( cursor ) { break ; } } return [ cursor , setCursor ] ; } ;