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

Multi tool use
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.





its because you are doing setState in getMousePosition method, setState trigger re-rending of the component.
– Mayank Shukla
Jun 30 at 9:17



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.

t1CZCYw,N i,N92dwmp 3,7vlC2YtIpfrg08,pe,SNqy,JLcpmMdF kDaVgUieaiH3MExhubO1G jXy
Ex5El7l,TS,kEqCWw,bS BpC,ijxUnR vWWfr

Popular posts from this blog

Delphi Android file open failure with API 26

.

Amasya