Components are rendering again and again after i set mouse move event listener for body in react js

Multi tool use
Components are rendering again and again after i set mouse move event listener for body in react js
I wrote a event listener for body to get the mouse position in react js
getMousePosition = (event) => {
if(this.props.navActiveClass === "active-sm"){
var mouseX = 0, mouseY = 0;
this.setState({
mouseX:event.pageX,
mouseY:event.pageY,
})
}
}
componentDidMount(){
document.body.addEventListener('mousemove', this.getMousePosition);
}
componentWillUnmount() {
document.body.removeEventListener('mousemove', this.getMousePosition);
}
after that whenever i move the mouse showing component is re-rendering again and again.
setState
getMousePosition
setState
If you are not using
mouseX
or mouseY
in your rendering, and you definitely don't want it to re-render, you could check if just mouseX
and mouseY
updated in shouldComponentUpdate.– Tholle
Jun 30 at 10:37
mouseX
mouseY
mouseX
mouseY
1 Answer
1
As @Mayank said, you are using setState with an on mousemove. this.setState({}) causes the component to rerender. You should keep those two values out of state.
You can put them into the constructor like this
constructor(props) {
super(props);
this.mouseX = 0;
this.mouseY = 0;
}
and then in your function you set them the same way, just without setState.
getMousePosition = (event) => {
if(this.props.navActiveClass === "active-sm"){
var mouseX = 0, mouseY = 0;
this.mouseX = event.pageX;
this.mouseY = event.pageY;
}
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
its because you are doing
setState
ingetMousePosition
method,setState
trigger re-rending of the component.– Mayank Shukla
Jun 30 at 9:17