QuizNot attempted
Spot the bug: derived state synced by an effect
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
datastill shows the old count, then the effect fixes it with a second render. - Paging that must restart on new data (
currentPageis never reset here!) belongs in the event that changes the filter, or remount the table withkey={filter}. - (
data?.lengthnext todata.sliceis also inconsistent: ifdatacould be undefined,slicethrows 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:
.lengthis free - memoize only expensive calculations.