Производительность падает после навигации по нескольким маршрутам — кажется, что неиспользуемая память (особенно состояния Redux или данные компонентов) не очищается эффективно.
Я не хочу реорганизовать каждую страницу (поскольку приложение довольно большое), поэтому я попытался реализовать наблюдатель за очисткой глобальной памяти, который запускается автоматически при изменении маршрута.
Вот что я сделал в своем App.js:
Код: Выделить всё
const MemoryCleanupWatcher = () => {
const location = useLocation();
useEffect(() => {
return () => {
console.log(`🚀 Route change detected → cleaning up memory...`);
import("./utils/memoryCleaner").then(({ cleanUpMemory }) => cleanUpMemory());
};
}, [location.pathname]);
return null;
};
// Added inside (Ionic + React setup)
{/* 👇 Memory cleanup watcher */}
{/* ...routes */}
- Очистить неиспользуемые кэши
- Сбросить некоторые фрагменты Redux
- Вручную разыменовать глобальные переменные
Код: Выделить всё
// utils/memoryCleaner.js
export const cleanUpMemory = () => {
try {
let before = null; // ✅ Declare outside to use later
let after = null;
if (typeof performance !== "undefined" && performance.memory) {
before = (performance.memory.usedJSHeapSize / 1024 / 1024).toFixed(2);
console.log(`🧠 Memory before cleanup: ${before} MB`);
}
// Example cleanup operations
// ----------------------------------------------------
// ✅ Remove custom global caches
for (const key in window) {
if (Object.prototype.hasOwnProperty.call(window, key)) {
if (key.startsWith("__tempCache__") || key.includes("cache")) {
delete window[key];
}
}
}
// ✅ Remove event listeners
if (window._resizeHandler) {
window.removeEventListener("resize", window._resizeHandler);
delete window._resizeHandler;
}
// ✅ Clear DOM nodes or old iframes (optional)
const strayIframes = document.querySelectorAll("iframe[data-temp='true']");
strayIframes.forEach((iframe) => iframe.remove());
// ✅ Force garbage collection (only works if devtools allow it)
if (typeof window.gc === "function") {
window.gc();
}
// Wait a tick, then log memory after cleanup
setTimeout(() => {
if (typeof performance !== "undefined" && performance.memory) {
after = (performance.memory.usedJSHeapSize / 1024 / 1024).toFixed(2);
console.log(`🧹 Memory after cleanup: ${after} MB`);
if (before !== null) {
const diff = (after - before).toFixed(2);
console.log(
diff > 0
? `⚠️ Memory increased by ${diff} MB (likely GC delay)`
: `✅ Memory decreased by ${Math.abs(diff)} MB`
);
}
} else {
console.log("🧹 Cleanup complete (performance.memory not supported in this browser).");
}
}, 20);
} catch (err) {
console.warn("⚠️ Memory cleanup error:", err);
}
};
Я вижу срабатывание console.log, но использование памяти (через Chrome DevTools) все равно растет после нескольких переходов.
Чего я хочу:
- Сохранять Redux только для просматриваемой в данный момент страницы/вкладки (не все состояние приложения).
- Автоматически очищать память или состояния Redux при изменении маршрутов, без ручной очистки на каждой странице.
Подробнее здесь: https://stackoverflow.com/questions/798 ... te-changes
Мобильная версия