React.js ~useEffect event handler~
In case you want to manipulate DOM that can not be handled by React, useEffect is required. React is used for managing UI. So it is proper to use useEffect for manipulating DOM. const Component = () => { const [h, s
In case you want to manipulate DOM that can not be handled by React, useEffect is required. React is used for managing UI. So it is proper to use useEffect for manipulating DOM.
const Component = () => {
const [h, setH] = useState(0);
useEffect(() => {
const handler = () => {
setH(h => (h + 1) % 360);
};
window.addEventListener("pointermove", handler);
return () => {
window.removeEventListener("pointermove", handler);
};
}, []);
return (
<div
style={{
backgroundColor: `hsl(${h}, 100%, 50%)`,
width: "100px",
height: "100px"
}}
/>
);
};
📰 Read the original article on Dev.to WebDev
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.