Created
April 6, 2022 06:35
-
-
Save dartess/109f8a5f6635496b2526166d19ace8fe to your computer and use it in GitHub Desktop.
Memory usage component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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