Efficient memory management is crucial in SSR to prevent memory leaks and ensure optimal performance.
Ensure that server-side instances of your application do not hold onto references longer than necessary:
let timer = setTimeout(() => {
// Task
}, 1000);
// Later in the code
clearTimeout(timer);
function onEvent() {
// Handler
}
element.addEventListener('click', onEvent);
// Later in the code
element.removeEventListener('click', onEvent);
Never override or extend global prototypes (e.g., Array.prototype
) as it can lead to memory leaks and unpredictable behavior across different instances.
// Bad Practice
Array.prototype.push = function(item) {
// Custom push logic
};
When possible, use weak references to allow garbage collection of unused objects.
const weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, 'Some value');
// obj can be garbage collected when no longer referenced elsewhere