Performance: Cleanup function
This affects interaction responsiveness and memory usage by properly cleaning up side effects in React components.
useEffect(() => {
const id = setInterval(() => {
console.log('tick');
}, 1000);
return () => clearInterval(id);
}, []);useEffect(() => {
const id = setInterval(() => {
console.log('tick');
}, 1000);
// No cleanup function
}, []);| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Effect without cleanup | No extra DOM nodes | No reflows | No paint cost | [X] Bad - causes memory leaks and CPU waste |
| Effect with cleanup | No extra DOM nodes | No reflows | No paint cost | [OK] Good - frees resources and improves responsiveness |
useEffect hook?useEffect?clearTimeout. Others either don't return a function or return the wrong value.function Timer() {
React.useEffect(() => {
const id = setInterval(() => console.log('tick'), 1000);
return () => {
clearInterval(id);
console.log('cleanup');
};
}, []);
return null;
}useEffect(() => {
window.addEventListener('resize', handleResize);
return window.removeEventListener('resize', handleResize);
}, []);return () => window.removeEventListener('resize', handleResize); to run on unmount.function SocketComponent({ url }) {
React.useEffect(() => {
const socket = new WebSocket(url);
socket.onmessage = (event) => console.log(event.data);
// What cleanup code is correct?
}, [url]);
return null;
}socket.close(). return () => { socket.close(); }; does this correctly.Pass the test and this pattern moves unknown