I'm writing a React application and I have a common scenario that I would like to know how to solve from design point of view rather than with workarounds.
Often I'm in a situation where I have to change a hook dependency inside the hook itself.
In this case I have a table and I'm writing a component that handles the pagination. The three main variables that the pagination is based on are: the number of rows, the number of the page, the number of items per page. Here's the hook:
const [page, setPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(5);
useEffect(() => {
let fixedItemsPerPage = itemsPerPage;
let fixedPage = page;
if (itemsPerPage > filteredRequests.length) {
fixedItemsPerPage = filteredRequests.length;
fixedPage = 1;
}
const paginatedFilteredRequests = filteredRequests.slice(
fixedItemsPerPage * (fixedPage - 1),
fixedItemsPerPage * fixedPage,
);
setVisibleRequests(paginatedFilteredRequests);
}, [filteredRequests, itemsPerPage, page]);
So, anytime one of those variables change, I re-run the hook and I adjust the array of visibleRequests based on the pagination variables.
The reason I need the auxiliar variables fixedItemsPerPage and fixedPage is because if I select a itemsPerPage that is higher than the length of the rows array the slice function will go out of bound, or if I select page 2 and then I adjust itemsPerPage to include all the items in the table I will still be in page 2 and it will show nothing instead of all the results.
Clearly this is a workaround, ideally I would like to set those variables with setItemsPerPage and setPage, but if I do that, I will cause an infinite render.
How can I solve the problem?
setVisibleRequeststhe state changing function forfilteredRequests?