Throttling Frequent Data in React
In this post we will make a custom hook that will update state on a set interval, even if it is passed new data 60 times per second

I have a somewhat unique problem. I have a function being called 60 times per second, and it never stops being called. Most examples for throttling or debouncing only invoke the function after a rest period. In the case of an ARKit session, this never ends. The function is called constantly.
In this post we will be making a small hook that will store data in a ref, and then every so often, push the data into state. This way our React tree won't render too often. Instead of 60 renders a second, we can control the frequency. At the same time, we will have the data fully up to date by the time state changes.
Let's take a look at my initial approach. This was copied across multiple files, so after this first attempt I decided to pull it into a custom hook.
export const useCameraPosition = ({debounceTime = 1000}: Props) => {
let cameraPositionRef = useRef<Camera>()
let [cameraPosition, setCameraPosition] = useState<Camera>()
useEffect(() => {
let changed: any
let timer = setInt…
Keep reading with a 7-day free trial
Subscribe to zach.codes to keep reading this post and get 7 days of free access to the full post archives.