Sometimes, we want to fix the throttle mousemove event keep throwing event.persist()
error issue with React.
In this article, we’ll look at how to fix the throttle mousemove event keep throwing event.persist()
error issue with React.
How to fix the throttle mousemove event keep throwing event.persist() error issue with React?
To fix the throttle mousemove event keep throwing event.persist() error issue with React, we can use the throttle
Lodash method with the event.persist
method.
For instamce, we can write:
import React, { useMemo } from "react";
import { throttle } from "lodash";
export default function App() {
const onMouseMove = useMemo(() => {
const throttled = throttle((e) => console.log(e.screenX), 300);
return (e) => {
e.persist();
return throttled(e);
};
}, []);
return (
<div>
<div onMouseMove={onMouseMove}>Content</div>
</div>
);
}
to define the onMouseMove
function that is defined by calling the useMemo
hook with a function that does the throttling with Lodash throttle
.
We throttle the (e) => console.log(e.screenX)
to run once every 300 milliseconds.
Then we return a function that calls e.persist
to persist the event.
And then we throttled mousemove event handler that we created with throttle
by calling it with e
.
Now when we move our move over the div, we should no longer see errors when calling event.persist
.
Conclusion
To fix the throttle mousemove event keep throwing event.persist() error issue with React, we can use the throttle
Lodash method with the event.persist
method.