How to Improve Core Web Vitals in a React Application :👈 👉:Common React Optimization Mistakes

How to Investigate Slow React Page Loads

How to Investigate Slow React Page Loads

1. Introduction

A React application may load slowly for several reasons, such as large JavaScript bundles, slow API responses, excessive component rendering, unoptimized images, or server performance issues.

The important point is to identify the actual bottleneck before making changes. Randomly adding useMemo, React.memo, or other optimizations may not solve the problem if the real issue is network latency or server response time.

A systematic investigation helps identify whether the delay occurs during:

  • Initial HTML document loading.
  • JavaScript downloading and execution.
  • React application initialization and rendering.
  • API requests and data processing.
  • Image, font, and other resource loading.
  • Client-side navigation between routes.

2. Understand the Page Loading Process

Before investigating performance, understand the major steps involved in loading a React application.

  1. Browser requests the page: The browser requests the HTML document from the server.
  2. HTML is downloaded: The browser receives the initial HTML.
  3. JavaScript and CSS are downloaded: The browser retrieves the application bundles and stylesheets.
  4. JavaScript is executed: React and application code are initialized.
  5. React renders components: The component tree is rendered and the browser updates the page.
  6. API requests complete: The application retrieves required data from backend services.
  7. Page becomes interactive: Users can interact with the application.

A delay in any of these steps can make the page appear slow.

3. Start with Browser Developer Tools

Chrome or Edge Developer Tools should be the first place to investigate slow page loads.

3.1 Network Tab

Open Developer Tools using F12 and select the Network tab.

Reload the page and inspect the following information:

  • Size: Amount of data downloaded.
  • Time: Time taken to complete each request.
  • Waterfall: Shows when requests start and finish.
  • Status: HTTP response status codes.
  • Initiator: Identifies what triggered a request.
  • Type: Identifies whether the resource is JavaScript, CSS, image, font, or API data.

Pay particular attention to large JavaScript files, slow API requests, images, and resources that block rendering.

3.2 Understand Network Timing

Select an individual request and open its Timing tab.

Timing Metric Meaning Possible Problem
Queueing Time spent waiting before the request starts. Browser resource prioritization or connection limits.
DNS Lookup Time required to resolve the domain name. DNS resolution delay.
Initial Connection Time required to establish a connection. Connection or network latency.
SSL Time required for the secure connection handshake. TLS handshake delay.
Waiting for Server Response (TTFB) Time until the first response byte arrives. Slow backend processing or server/network delay.
Content Download Time required to download the response body. Large response or slow transfer.

Important: High TTFB does not automatically mean the backend is slow. It can also include network latency and other server-side delays. Investigate server logs and distributed traces to identify the actual cause.

3.3 Disable Cache During Investigation

Enable Disable cache in the Network tab while Developer Tools is open.

This helps investigate the first-visit experience without relying on previously cached resources. Also test with caching enabled to understand repeat-visit performance.

4. Investigate JavaScript Bundle Size

Large JavaScript bundles are a common reason for slow React application startup.

When users open a page, the browser may need to download, parse, compile, and execute JavaScript before the application becomes fully interactive.

4.1 Identify Large JavaScript Files

In the Network tab:

  1. Filter resources by JS.
  2. Sort by transferred size.
  3. Identify unusually large JavaScript files.
  4. Check whether the initial page downloads code that is not immediately required.

4.2 Use Bundle Analysis

For applications built with Vite, you can use a bundle visualizer to inspect which dependencies contribute most to the production bundle.

Example installation:

npm install --save-dev rollup-plugin-visualizer

Example Vite configuration:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({
  plugins: [
    react(),
    visualizer({
      open: true,
      filename: 'bundle-report.html'
    })
  ]
});

Build the application:

npm run build

Open the generated bundle report to identify large dependencies and modules.

4.3 Optimize Bundle Size

  • Remove unused dependencies.
  • Use tree-shakable imports.
  • Split large application features into separate chunks.
  • Lazy-load routes and components that are not immediately needed.
  • Avoid importing entire utility libraries when only a few functions are required.
  • Use production builds rather than development builds for performance testing.

4.4 Use Code Splitting

Instead of loading every page component immediately, load a component when the user needs it.

import { lazy, Suspense } from 'react';
const Reports = lazy(() => import('./Reports'));
function App() {
  return (
    <Suspense fallback={<p>Loading reports...</p>}>
      <Reports />
    </Suspense>
  );
}
export default App;

This allows the Reports component to be downloaded separately when required.

Note: For route-based applications, configure lazy loading at the route level. This helps avoid downloading code for unrelated pages during initial loading.

5. Investigate React Rendering Performance

Sometimes JavaScript downloads quickly, but the page still takes time to become usable because React performs expensive rendering work.

5.1 Use React Developer Tools Profiler

Install React Developer Tools in Chrome or Edge.

  1. Open Developer Tools.
  2. Select the Profiler tab.
  3. Start recording.
  4. Reload the page or perform the slow interaction.
  5. Stop recording.
  6. Inspect the components that took the most rendering time.

The Profiler helps identify:

  • Components that render frequently.
  • Components that take a long time to render.
  • Unnecessary child component renders.
  • Expensive updates caused by state or context changes.

5.2 Identify Unnecessary Re-renders

Consider this example:

function ProductList({ products }) {
  return (
    <div>
      {products.map(product => (
        <ProductItem
          key={product.id}
          product={product}
        />
      ))}
    </div>
  );
}

If the parent renders frequently, its child components may also render. Investigate whether those renders are necessary before applying optimization.

For a child component that receives unchanged props, React.memo may help avoid unnecessary renders.

const ProductItem = React.memo(function ProductItem({ product }) {
  return (
    <div>
      <h3>{product.name}</h3>
      <p>{product.price}</p>
    </div>
  );
});

Important: React.memo does not prevent rendering when the component's own state or consumed context changes. It is useful only when avoiding a particular render provides a measurable benefit.

5.3 Investigate Expensive Calculations

Complex calculations performed during rendering can make a component slow.

Example:

function ProductList({ products }) {
  const filteredProducts = products.filter(product => {
    return product.price > 1000;
  });
  return (
    <div>
      {filteredProducts.map(product => (
        <p key={product.id}>{product.name}</p>
      ))}
    </div>
  );
}

If filtering or processing is expensive and the inputs do not change frequently, consider useMemo.

import { useMemo } from 'react';
function ProductList({ products }) {
  const filteredProducts = useMemo(() => {
    return products.filter(product => {
      return product.price > 1000;
    });
  }, [products]);
  return (
    <div>
      {filteredProducts.map(product => (
        <p key={product.id}>{product.name}</p>
      ))}
    </div>
  );
}

Note: useMemo caches a calculation between renders when its dependencies remain unchanged. It does not make the first calculation faster. Avoid using it for every calculation without measuring the benefit.

6. Investigate Slow API Responses

A React page may appear slow because it waits for backend APIs before displaying important content.

6.1 Identify Slow API Requests

In the Network tab, select the Fetch/XHR filter.

Check:

  • Which API takes the longest time?
  • Are multiple APIs called unnecessarily?
  • Are APIs being called repeatedly?
  • Are large amounts of data being returned?
  • Does the page wait for multiple independent APIs one after another?

6.2 Avoid Sequential API Calls When Possible

Suppose a dashboard requires three independent APIs.

Less efficient approach:

const users = await fetch('/api/users');
const orders = await fetch('/api/orders');
const products = await fetch('/api/products');

Each request waits for the previous request to finish.

Better approach when requests are independent:

const [users, orders, products] = await Promise.all([
  fetch('/api/users'),
  fetch('/api/orders'),
  fetch('/api/products')
]);

Promise.all() allows independent requests to run concurrently. It rejects if any promise rejects, so handle errors appropriately.

6.3 Avoid Fetching Unnecessary Data

  • Request only the fields required by the page.
  • Use pagination for large collections.
  • Implement filtering and sorting on the server for large datasets when appropriate.
  • Cache reusable API responses where suitable.
  • Avoid repeated requests caused by incorrect effect dependencies.
  • Consider server-side aggregation when a page requires many related API calls.

6.4 Investigate Backend Performance

If an API is consistently slow, investigate the backend rather than trying to solve everything in React.

For an ASP.NET Core backend, check:

  • SQL query execution time.
  • Database indexes.
  • Unnecessary database queries.
  • External service response times.
  • Large response payloads.
  • Server CPU and memory usage.
  • Application logs and distributed traces.

7. Investigate Image and Static Resource Loading

Large images, fonts, and other static resources can delay page rendering and increase the amount of data downloaded.

7.1 Optimize Images

  • Use modern formats such as WebP or AVIF where supported.
  • Resize images to match their displayed dimensions.
  • Use responsive images with srcset when appropriate.
  • Specify image width and height to reduce layout shifts.
  • Lazy-load images below the initial viewport.
  • Do not lazy-load the important hero image when it is the likely Largest Contentful Paint element.

Example:

<img
  src="/images/product.webp"
  alt="Product"
  width="400"
  height="300"
  loading="lazy"
/>

For an important above-the-fold image, prioritize loading when appropriate:

<img
  src="/images/hero.webp"
  alt="Featured content"
  width="1200"
  height="600"
  fetchPriority="high"
/>

7.2 Optimize Fonts

  • Use only the required font weights and styles.
  • Prefer modern font formats such as WOFF2.
  • Preload only critical fonts when appropriate.
  • Use a suitable fallback font.
  • Check whether third-party font requests delay rendering.

8. Investigate Core Web Vitals

Core Web Vitals help measure important aspects of real-world user experience.

Metric Measures Good Needs Improvement Poor
LCP Loading performance. ≤ 2.5 seconds 2.5–4 seconds > 4 seconds
INP Interaction responsiveness. ≤ 200 ms 200–500 ms > 500 ms
CLS Visual stability. ≤ 0.1 0.1–0.25 > 0.25

These thresholds are assessed at the 75th percentile of real user visits, separately for mobile and desktop.

8.1 Largest Contentful Paint (LCP)

LCP measures how quickly the largest visible content element is rendered.

Common causes of poor LCP:

  • Slow server response.
  • Large hero images.
  • Render-blocking CSS or JavaScript.
  • Late discovery of important resources.
  • Slow font loading.

Investigate the actual LCP element and optimize the resource or rendering path responsible for it.

8.2 Interaction to Next Paint (INP)

INP measures how responsive the page is to user interactions throughout a visit.

Common causes of poor INP:

  • Long-running JavaScript tasks.
  • Expensive event handlers.
  • Large component trees being updated.
  • Heavy calculations on the main thread.
  • Excessive DOM updates.

Use the Performance panel to identify long tasks and inspect the JavaScript responsible for them.

8.3 Cumulative Layout Shift (CLS)

CLS measures unexpected layout movement during page loading and use.

Common causes:

  • Images without specified dimensions.
  • Advertisements without reserved space.
  • Dynamic content inserted above existing content.
  • Font changes that alter text layout.

Reserve space for images and dynamic content to reduce unexpected movement.

9. Use Lighthouse and PageSpeed Insights

These tools help identify performance problems and suggest improvements.

9.1 Lighthouse

In Chrome Developer Tools:

  1. Open the Lighthouse tab.
  2. Select the Performance category.
  3. Choose the appropriate device setting.
  4. Generate the report.
  5. Review performance metrics and opportunities.

9.2 PageSpeed Insights

Use Google PageSpeed Insights to analyze a publicly accessible page.

It provides:

  • Lab performance data.
  • Available real-user field data.
  • Core Web Vitals assessment.
  • Recommendations for improving loading and responsiveness.

Important: Lighthouse lab tests do not directly measure real-user INP. Total Blocking Time (TBT) can help diagnose main-thread blocking in a lab test, but it is not the same metric as INP.

10. Investigate Client-Side Routing

In a React single-page application, navigating between routes usually does not require a complete browser page reload. However, route transitions can still be slow.

Common causes include:

  • Large route components.
  • Fetching data every time a route is opened.
  • Unnecessary component remounting.
  • Heavy calculations during route rendering.
  • Loading all route dependencies in the initial bundle.

Possible improvements:

  • Lazy-load route components.
  • Cache reusable API responses.
  • Keep shared layouts mounted where appropriate.
  • Show useful loading states.
  • Avoid unnecessary data fetching during navigation.

11. Use Performance Monitoring in Production

Local testing is useful, but it may not represent the experience of real users with different devices, networks, and locations.

Real User Monitoring (RUM) helps collect performance data from actual application visits.

The web-vitals package can collect Core Web Vitals.

Install the package:

npm install web-vitals

Example:

import {
  onCLS,
  onINP,
  onLCP
} from 'web-vitals';
function sendToAnalytics(metric) {
  const body = JSON.stringify({
    name: metric.name,
    value: metric.value,
    id: metric.id
  });
  if (navigator.sendBeacon) {
    navigator.sendBeacon('/api/performance', body);
  } else {
    fetch('/api/performance', {
      method: 'POST',
      body,
      headers: {
        'Content-Type': 'application/json'
      },
      keepalive: true
    });
  }
}
onCLS(sendToAnalytics);
onINP(sendToAnalytics);
onLCP(sendToAnalytics);

Initialize this monitoring once during application startup rather than registering the callbacks every time a component renders. Ensure the monitoring endpoint handles the payload correctly and avoid collecting sensitive user information.

12. Common Performance Investigation Mistakes

Mistake Why It Is a Problem Better Approach
Using useMemo everywhere Adds complexity without necessarily improving performance. Profile first and memoize expensive calculations when useful.
Optimizing React before checking Network The actual problem may be a slow API or large resource. Inspect network requests first.
Testing only in development mode Development behavior may differ from production. Test optimized production builds.
Ignoring image sizes Large images increase download and rendering time. Resize, compress, and prioritize images correctly.
Loading every route immediately Increases the initial JavaScript download. Use route-based code splitting.
Ignoring backend performance Frontend optimization cannot fix slow database queries. Trace slow requests through the backend.
Measuring only on a fast computer Does not represent users on slower devices or networks. Test different device and network conditions.

13. Practical Investigation Workflow

Follow this sequence when a React page is reported as slow.

  1. Reproduce the problem: Identify the affected page, device, browser, and network conditions.
  2. Measure the baseline: Record loading time and relevant performance metrics before making changes.
  3. Inspect Network: Identify slow APIs, large JavaScript bundles, and large static resources.
  4. Check TTFB: Investigate whether the initial document or API response is delayed.
  5. Inspect JavaScript execution: Use the Performance panel to find long tasks and expensive execution.
  6. Profile React: Identify expensive component renders and unnecessary updates.
  7. Check Core Web Vitals: Investigate LCP, INP, and CLS.
  8. Identify the root cause: Determine whether the bottleneck is frontend, backend, network, or a combination.
  9. Apply targeted optimization: Fix the largest measured bottleneck first.
  10. Measure again: Compare results against the original baseline.
  11. Monitor production: Verify that real users experience the improvement.

14. Example: Investigating a Slow Dashboard

Suppose a React dashboard takes approximately 7 seconds to become usable.

During investigation, the following issues are discovered:

Finding Observation Action
Initial JavaScript bundle Large bundle containing unrelated report modules. Introduce route-based code splitting.
Dashboard APIs Three independent APIs execute sequentially. Run independent requests concurrently.
React rendering A large table renders thousands of rows. Use list or table virtualization.
Images Large images are downloaded unnecessarily. Resize and optimize images.
Database One API performs an expensive database query. Review query execution and indexes.

After addressing the identified bottlenecks, measure the page again under comparable conditions. Do not assume a particular improvement until the new measurements confirm it.

15. Tools for React Performance Investigation

Tool Purpose
Chrome/Edge Network Tab Investigate network requests, download sizes, and request timing.
Chrome/Edge Performance Tab Analyze JavaScript execution, long tasks, rendering, and main-thread activity.
React Developer Tools Profiler Identify expensive React component renders.
Lighthouse Run lab-based performance audits.
PageSpeed Insights Review lab results and available real-user performance data.
Bundle Visualizer Identify large dependencies and JavaScript modules.
Application Performance Monitoring Monitor frontend and backend performance in production.
Distributed Tracing Follow requests across frontend APIs and backend services.

16. Interview Questions and Answers

Q1. How do you investigate a slow React page?

I first reproduce the issue and establish a performance baseline. I use browser Network tools to inspect API response times, JavaScript bundle sizes, and resource loading. Then I use the Performance panel to identify long tasks and React Profiler to find expensive component renders. After identifying the bottleneck, I apply targeted optimizations and measure the results again.

Q2. How do you identify whether the problem is frontend or backend?

I inspect the Network tab and analyze request timing. If the browser spends significant time waiting for an API response, I investigate the backend using logs, database query metrics, and distributed tracing. If the API responds quickly but the page remains slow, I investigate JavaScript execution, React rendering, and browser layout work.

Q3. What is the difference between Lighthouse and React Profiler?

Lighthouse audits overall page performance, accessibility, and other web quality areas. React Profiler focuses on React component rendering and helps identify components that render frequently or consume significant rendering time.

Q4. How can a large JavaScript bundle affect page loading?

A large bundle takes longer to download, parse, compile, and execute. This can delay application startup and user interaction. I use bundle analysis, tree shaking, code splitting, and lazy loading to reduce the initial JavaScript workload.

Q5. How do you investigate unnecessary React re-renders?

I use React Developer Tools Profiler to record component updates and identify which components render frequently. I then investigate state changes, context updates, and changing props. Where measurement shows a benefit, I use techniques such as React.memo, useMemo, and useCallback.

Q6. What is the difference between LCP and INP?

LCP measures loading performance by tracking when the largest content element becomes visible. INP measures interaction responsiveness by evaluating the delay between user interactions and the next visual update.

Q7. Does useMemo solve slow page loading?

No. useMemo can avoid repeating expensive calculations when dependencies remain unchanged. It does not solve large bundle downloads, slow APIs, server delays, or expensive first-time calculations. The actual bottleneck must be identified first.

Q8. Why should performance be tested in production mode?

Development builds include additional checks and development-related overhead. Production builds use optimizations such as minification and dead-code elimination. Therefore, production builds provide a more representative measure of real application performance.

Q9. What is the purpose of distributed tracing in performance investigation?

Distributed tracing helps follow a request across multiple services. It helps identify where time is spent, such as an API gateway, application service, database, or external dependency.

Q10. How do you ensure that an optimization actually worked?

I compare performance measurements before and after the change under comparable conditions. I also monitor production data to verify that the improvement is visible to real users and has not introduced other problems.

17. Final Checklist

  • Reproduce the slow-loading behavior.
  • Measure the initial page-loading performance.
  • Inspect Network requests and waterfall timing.
  • Identify large JavaScript bundles.
  • Analyze slow API responses.
  • Check server response time and database queries.
  • Profile React component rendering.
  • Identify long-running JavaScript tasks.
  • Optimize images, fonts, and static resources.
  • Review LCP, INP, and CLS.
  • Test the optimized production build.
  • Compare measurements after every major change.
  • Monitor real-user performance in production.

18. Key Takeaways

  • Always measure before optimizing.
  • Start with Network and Performance tools to locate the bottleneck.
  • Large JavaScript bundles can delay application startup.
  • Slow APIs and database queries can make a React page appear slow.
  • React Profiler helps identify expensive component rendering.
  • Core Web Vitals help measure loading, responsiveness, and visual stability.
  • Use targeted optimizations instead of applying memoization everywhere.
  • Validate improvements with production measurements and real-user monitoring.

Golden Rule: Do not optimize React blindly. First identify whether the bottleneck is network, server, JavaScript execution, React rendering, or resource loading. Fix the actual bottleneck and measure the improvement.

🔙
How to Improve Core Web Vitals in a React Application :👈 👉:Common React Optimization Mistakes

Comments and Discussion