CMU Coding Bootcamp
1// Import necessary hooks from React library
2import { useEffect, useCallback } from 'react';
3
4// Define the PerformanceMonitor functional component
5function PerformanceMonitor() {
6 // Use useCallback hook to memoize the performance measurement function, preventing unnecessary re-renders
7 const measurePerformance = useCallback(() => {
8 // Check if the browser supports the Performance API
9 if (window.performance) {
10 // Get navigation timing data
11 const navigation = performance.getEntriesByType('navigation')[0];
12 // Get paint timing data
13 const paintEntries = performance.getEntriesByType('paint');
14
15 // Log navigation timing data to the console
16 console.log('Navigation Timing:', {
17 DNS: navigation.domainLookupEnd - navigation.domainLookupStart, // Calculate DNS lookup time
18 TLS: navigation.connectEnd - navigation.connectStart, // Calculate TLS handshake time
19 TTFB: navigation.responseStart - navigation.requestStart, // Calculate Time to First Byte
20 DOMContentLoaded: navigation.domContentLoadedEventEnd - navigation.navigationStart, // Calculate DOMContentLoaded time
21 Load: navigation.loadEventEnd - navigation.navigationStart // Calculate page load time
22 });
23
24 // Log paint timing data to the console
25 console.log('Paint Timing:', {
26 FP: paintEntries.find(entry => entry.name === 'first-paint')?.startTime, // Get First Paint time
27 FCP: paintEntries.find(entry => entry.name === 'first-contentful-paint')?.startTime // Get First Contentful Paint time
28 });
29 }
30 // The empty dependency array ensures that this function is only created once
31 }, []);
32
33 // Use useEffect hook to add and remove the 'load' event listener
34 useEffect(() => {
35 // Add 'load' event listener to measure performance after the page has fully loaded
36 window.addEventListener('load', measurePerformance);
37 // Return a cleanup function to remove the event listener when the component unmounts
38 return () => window.removeEventListener('load', measurePerformance);
39 // Add measurePerformance to the dependency array to ensure the listener is updated when the function changes
40 }, [measurePerformance]);
41
42 // This component doesn't render anything visually
43 return null;
44}
45
46
47// Export the PerformanceMonitor component as the default export
48export default PerformanceMonitor;