Skip to content

Instantly share code, notes, and snippets.

@mithi
Created November 15, 2021 08:11
Show Gist options
  • Save mithi/f023accdfd00cca7aef57d5457e3edb5 to your computer and use it in GitHub Desktop.
Save mithi/f023accdfd00cca7aef57d5457e3edb5 to your computer and use it in GitHub Desktop.
import { useState, useCallback } from 'react'
const getTotalPages = (total: number, perPage: number) => Math.ceil(total / perPage)
const usePagination = () => {
const [state, setPaginationState] = useState<{
totalItems: number
itemsPerPage: number
currentPage: number
}>({ totalItems: 0, itemsPerPage: 1, currentPage: 1 })
const totalPages = Math.max(getTotalPages(state.totalItems, state.itemsPerPage), 1)
const currentStartItem = (state.currentPage - 1) * state.itemsPerPage
const currentEndItem = currentStartItem + state.itemsPerPage
const isLastPage = state.currentPage === totalPages
const isFirstPage = state.currentPage === 1
const resetPaginationParams = useCallback((totalItems: number, itemsPerPage: number) => {
setPaginationState({ totalItems, itemsPerPage, currentPage: 1 })
}, [])
const goToNextPage = useCallback(() => {
setPaginationState((prev) => {
return { ...prev, currentPage: isLastPage ? 1 : prev.currentPage + 1 }
})
}, [isLastPage])
const goToPreviousPage = useCallback(() => {
setPaginationState((prev) => {
return {
...prev,
currentPage: isFirstPage ? totalPages : prev.currentPage - 1,
}
})
}, [isFirstPage, totalPages])
const goToPage = useCallback(
(newPage: number) => {
if (newPage >= totalPages || newPage < 1) {
return
}
setPaginationState((prev) => ({ ...prev, currentPage: newPage }))
},
[totalPages],
)
return {
resetPaginationParams,
goToNextPage,
goToPreviousPage,
currentPage: state.currentPage,
goToPage,
isLastPage,
isFirstPage,
totalPages,
currentStartItem,
currentEndItem,
}
}
export default usePagination
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment