Skip to content

Instantly share code, notes, and snippets.

@dartess
Created April 6, 2022 06:35
Show Gist options
  • Save dartess/109f8a5f6635496b2526166d19ace8fe to your computer and use it in GitHub Desktop.
Save dartess/109f8a5f6635496b2526166d19ace8fe to your computer and use it in GitHub Desktop.
Memory usage component
import * as React from 'react';
export const MemoryUsage = () => {
const [percent, setPercent] = React.useState<string | number>('-');
const color = (() => {
if (typeof percent === 'string') {
return 'white';
}
if (percent < 50) {
return 'green';
}
if (percent < 80) {
return 'yellow';
}
return 'red';
})();
React.useEffect(() => {
const timer = window.setInterval(() => {
const { memory } = window.performance as any;
const bytes = memory.usedJSHeapSize;
const limit = memory.jsHeapSizeLimit;
setPercent((bytes / limit) * 100);
}, 1000);
return () => {
window.clearInterval(timer);
};
});
return ReactDOM.createPortal(
<div
style={{
position: 'fixed',
right: 0,
bottom: 0,
pointerEvents: 'none',
padding: 20,
fontSize: '3em',
color,
backgroundColor: 'rgba(0, 0, 0, 0.3)',
zIndex: 19999,
}}
>
{typeof percent === 'string' ? percent : `${percent.toFixed(1)}%`}
</div>,
document.body
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment