Skip to content

QuizNot attempted

Spot the bug: derived state synced by an effect

What is the problem with totalItems?
const [totalItems, setTotalItemsLength] = useState(0);
const [displayData, setDisplayData] = useState<TableData[]>([]);
useEffect(() => {
setTotalItemsLength(data?.length);
setDisplayData(data.slice(0, itemsPerPage));
}, [data, itemsPerPage]);
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • It is derived from props, so compute it in render (data.length); the effect adds an extra render where it is out of sync
  • Anything you can calculate from props or state should be calculated during render.
  • Here the first render after new data still shows the old count, then the effect fixes it with a second render.
  • Paging that must restart on new data (currentPage is never reset here!) belongs in the event that changes the filter, or remount the table with key={filter}.
  • (data?.length next to data.slice is also inconsistent: if data could be undefined, slice throws anyway.) Not the recommended pattern: React's docs list it under "You might not need an effect".
  • Not a ref: a ref wouldn't update the UI and still duplicates the data.
  • Not useMemo: .length is free
  • memoize only expensive calculations.