This is a example of connecting to an external system I took from React website:
export default function App() {
const [position, setPosition] = useState({ x: 0, y: 0 });
useEffect(() => {
function handleMove(e) {
setPosition({ x: e.clientX, y: e.clientY });
}
window.addEventListener('pointermove', handleMove);
return () => {
window.removeEventListener('pointermove', handleMove);
};
}, []);
return (
<div style={{
position: 'absolute',
backgroundColor: 'pink',
borderRadius: '50%',
opacity: 0.6,
transform: `translate(${position.x}px, ${position.y}px)`,
pointerEvents: 'none',
left: -20,
top: -20,
width: 40,
height: 40,
}} />
);
}
I have the same result as well with:
export default function App() {
const [position, setPosition] = useState({ x: 0, y: 0 });
function handleMove(e) {
setPosition({ x: e.clientX, y: e.clientY });
}
window.addEventListener('pointermove', handleMove);
return (
// Same things...
);
}
The only different thing is useEffect
callback executed after the render phase. So I want to know if it’s important to use useEffect
when I do something with DOM.
Any help would be greatly appreciated!
2
Answers
Without
useEffect
, the event listener will be added each time the component rerenders (e.g. when one of the state variables changes). You can quickly get enough event listeners to cause a noticeable impact on performance.useEffect
with an empty dependency array ensures that the code is only run when the component is initially mounted.The cleanup function returned from
useEffect
handles removing the event listener when the component unmounts.It is never a good idea to cause side effects during the render phase.
In React world every component has a lifecycle in which it is created, mounted, updated and unmounted.
Using the useEffect hook with an empty array as its dependency, help you to add an event listener on the mounting phase of the component’s life cycle and to remove an event listener by returning a callback function which is executed on the unmounting phase of the component’s lifecycle.
The problem of adding an event listener without using useEffect in this code is that the event listener will be added each time the component re-renders due to state changes. Eventually causing performance issues.