The core rAF loop wasn't hard to sketch out but I kept second-guessing the cleanup.
Start by outlining the hook's API and core implementation using requestAnimationFrame and a rolling window (e.g., a circular buffer of timestamps). Then discuss edge cases like tab backgrounding and strategies to minimize re-renders, such as throttling state updates or using refs. Finally, mention cleanup and potential performance trade-offs.
Pro tip: Emphasize that requestAnimationFrame pauses when the tab is backgrounded, so the hook should detect visibility changes and either pause updates or reset the window to avoid misleading FPS values. Also, consider using a ref to store the FPS value and only trigger re-renders at a lower frequency (e.g., once per second) to balance accuracy and performance.
Decide what the hook returns (e.g., a number representing FPS) and how often it updates. Use useState for the FPS value and useRef for mutable variables like frame timestamps and the animation frame ID.
Use requestAnimationFrame to recursively call a function that records the current timestamp, calculates the time delta from the previous frame, and maintains a rolling window of recent frame durations (e.g., last 60 frames). Compute FPS as the reciprocal of the average frame duration.
In a useEffect cleanup, cancel the animation frame. Also, listen to the visibilitychange event to pause the loop when the tab is hidden and resume when visible, resetting the rolling window to avoid skewed data.
Throttle state updates to avoid re-rendering on every frame. For example, update the FPS state only once per second or when the value changes significantly. Alternatively, return a ref and let the consumer decide when to read it.
Mention the trade-off between accuracy and performance: a larger rolling window smooths the value but reacts slower to changes. Also, note that requestAnimationFrame is tied to the display refresh rate, so FPS may be capped at 60 or 120 Hz.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.