0

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?

1 Answer 1

1

Putting the data alone into state wouldn't really help - it's never recalculated from the JSON, after all. The issue is that the .slice occurs every render. A better approach than state to keep this from being done every time would be to use useMemo.

const itemsToDisplay = useMemo(() => {
  const indexFinalItem = pageInView * itemsOnPage;
  const indexFirstItem = indexFinalItem - itemsOnPage;
  return data.slice(
    indexFirstItem,
    indexFinalItem
  );
}, [pageInView, itemsOnPage]);

This way, those calculations including the .slice occur only when pageInView or itemsOnPage change.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.