Understanding React's useEffect and Event Listeners: A Deep Dive
Have you ever wondered how React components can maintain active event listeners without re-registering them on every render? Let's unravel this mystery by examining a common use case: tracking mouse coordinates. The Puzzle Consider this React component that tracks mouse position: import React from 'react'; function MouseCoords() { const [mousePosition, setMousePosition] = React.useState({ x: 0, y: 0, }); React.useEffect(() => { function handleMouseMove(event) { setMousePosition({ x: event.clientX, y: event.clientY, }); } window.addEventListener('mousemove', handleMouseMove); }, []); return ( {mousePosition.x} / {mousePosition.y} ); } export default MouseCoords; Here's the interesting part: the empty dependency array ([]) means our useEffect only runs once, yet the component still updates when we move our mouse. How does this work?
Have you ever wondered how React components can maintain active event listeners without re-registering them on every render? Let's unravel this mystery by examining a common use case: tracking mouse coordinates.
The Puzzle
Consider this React component that tracks mouse position:
import React from 'react';
function MouseCoords() {
const [mousePosition, setMousePosition] = React.useState({
x: 0,
y: 0,
});
React.useEffect(() => {
function handleMouseMove(event) {
setMousePosition({
x: event.clientX,
y: event.clientY,
});
}
window.addEventListener('mousemove', handleMouseMove);
}, []);
return (
<div className="wrapper">
<p>
{mousePosition.x} / {mousePosition.y}
</p>
</div>
);
}
export default MouseCoords;
Here's the interesting part: the empty dependency array ([]
) means our useEffect
only runs once, yet the component still updates when we move our mouse. How does this work?