import { useEffect , useReducer , useCallback , useRef } from 'react' ; import { PaginationPayload } from '../types' ; typedef PaginationProps property { number } page property { number } perPage property { Function } setPage property { Function } setPerPage property { Function } setPagination export interface PaginationHookResult { page : number ; perPage : number ; pagination : PaginationPayload ; setPage : ( page : number ) => void ; setPerPage : ( perPage : number ) => void ; setPagination : ( pagination : PaginationPayload ) => void ; } const paginationReducer = ( prevState , nextState ) : PaginationPayload => { return { ... prevState , ... nextState , } ; } ; const defaultPagination = { page : 1 , perPage : 25 , } ; example param { number } initialPagination returns { PaginationHookResult } export default ( initialPagination = { } ) : PaginationHookResult => { const [ pagination , setPagination ] = useReducer ( paginationReducer , { ... defaultPagination , ... initialPagination , } ) ; const isFirstRender = useRef ( true ) ; const setPerPage = useCallback ( perPage => setPagination ( { perPage } ) , [ ] ) ; const setPage = useCallback ( page => setPagination ( { page } ) , [ ] ) ; useEffect ( ( ) => { if ( isFirstRender . current ) { isFirstRender . current = false ; return ; } setPerPage ( initialPagination . perPage || 25 ) ; } , [ initialPagination . perPage , setPerPage ] ) ; return { page : pagination . page , perPage : pagination . perPage , pagination , setPage , setPerPage , setPagination , } ; } ;