React.js throttle mousemove event keep throwing event.persist() error
e.persist needs to be called synchronously with the event, the handler can be called asynchronously. Here is a fix:
class Tool extends React.Component {
constructor(props) {
super(props);
this._throttledMouseMove = _.throttle(this._throttledMouseMove.bind(this), 2000);
}
_throttledMouseMove = (e) => {
console.log(e.screenX);
}
render() {
return (
<div ref="tool" className="tool">
<div ref="toolBody"
className="tool__body"
onMouseMove={this._onMouseMove}>
</div>
</div>
)
}
_onMouseMove = (e) => {
e.persist();
this._throttledMouseMove(e);
}
}
ReactDOM.render(<Tool/>, document.querySelector('.main'))
The relevant change is calling _onMouseMove directly from the event, and setting up a second method to actually handle event that's been throttled.
With hooks:
const Tool = () => {
const onMouseMove = useMemo(() => {
const throttled = _.throttle(e => console.log(e.screenX), 300);
return e => {
e.persist();
return throttled(e);
};
}, []);
return (
<div className="tool">
<div className="tool__body" onMouseMove={onMouseMove}>
Content
</div>
</div>
);
};