I have a react app that contains a component like this where I am displaying pages of data that are imported from a local json file:
import data from "data.json"
function myComponent() {
const [pageInView, setPageInView] = useState(1);
const [itemsOnPage, setItemsOnPage] = useState(15);
const indexFinalItem = pageInView * itemsOnPage;
const indexFirstItem = indexFinalItem - itemsOnPage;
const itemsToDisplay = data.slice(
indexFirstItem,
indexFinalItem
);
--- rest of component ---
}
The feedback I have got on this section of code is that I “can avoid recalculating (slicing) on every render by placing the data in a state”. I am having trouble understanding this and wondering if anyone could expand a bit on the optimization of this code?