Performance: Unmounting phase
This affects how quickly the browser can remove components and free up memory, impacting interaction responsiveness and visual stability.
useEffect(() => {
return () => {
// lightweight cleanup or defer heavy tasks
if ('requestIdleCallback' in window) {
requestIdleCallback(() => {
// perform heavy cleanup asynchronously
});
} else {
// fallback for browsers without requestIdleCallback
setTimeout(() => {
// perform heavy cleanup asynchronously
}, 0);
}
};
}, []);useEffect(() => {
return () => {
// heavy synchronous cleanup like large DOM manipulations or complex calculations
for (let i = 0; i < 1000000; i++) {
// simulate heavy cleanup
}
};
}, []);| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous cleanup in unmount | Multiple DOM removals and complex JS | Triggers multiple reflows | High paint cost due to layout thrashing | [X] Bad |
| Lightweight or deferred cleanup | Minimal DOM changes, async cleanup | Single or no reflow during unmount | Low paint cost, smooth transition | [OK] Good |
useEffect hook?import React, { useEffect } from 'react';
function Timer() {
useEffect(() => {
const id = setInterval(() => console.log('Tick'), 1000);
return () => {
clearInterval(id);
console.log('Cleanup');
};
}, []);
return <div>Timer running</div>;
}import React, { useEffect } from 'react';
function Listener() {
useEffect(() => {
window.addEventListener('resize', () => console.log('Resized'));
}, []);
return <div>Listening</div>;
}useEffect. Which is the best way to ensure the connection closes properly when the component unmounts?useEffect(() => {
const socket = new WebSocket('wss://example.com');
socket.onmessage = (event) => console.log(event.data);
// What should go here?
}, []);socket.close() ensures the connection closes when the component unmounts, preventing resource leaks.socket.close() to close the connection -> Option APass the test and this pattern moves unknown