Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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