DEV Community

Cover image for React Too Slow? Here's How to Fix It!
A.R
A.R

Posted on

React Too Slow? Here's How to Fix It!

  1. Analyze and Monitor Performance Use tools to find bottlenecks:

React DevTools: Inspect your component hierarchy and identify re-render issues.

npm install --save-dev @react-devtools/extension

Enter fullscreen mode Exit fullscreen mode

Use it in your browser to check for unnecessary renders.

VS Code Extensions:

ESLint: Ensures clean and optimized code.
Prettier: Enforces consistent code formatting.
Code Time: Tracks your coding habits and focuses on slow parts.

  1. Optimize Rendering Use React.memo: Wrap functional components with React.memo to avoid unnecessary re-renders.
import React, { memo } from 'react';

const MyComponent = memo(({ prop }) => {
  console.log('Rendering MyComponent');
  return <div>{prop}</div>;
});

export default MyComponent;

Enter fullscreen mode Exit fullscreen mode

Use useCallback and useMemo: Prevent new function instances on every render.

jsx
Copy code

import React, { useState, useCallback, useMemo } from 'react';

const App = () => {
  const [count, setCount] = useState(0);

  const expensiveComputation = useMemo(() => {
    console.log('Expensive computation');
    return count * 2;
  }, [count]);

  const handleClick = useCallback(() => {
    setCount((prev) => prev + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Double: {expensiveComputation}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

If you feel that React is slow in your project, there are several steps you can take to optimize its performance. Here's a practical guide with changes in your VS Code setup, tools, and coding techniques:

  1. Analyze and Monitor Performance Use tools to find bottlenecks:

React DevTools: Inspect your component hierarchy and identify re-render issues.

bash
Copy code
npm install --save-dev @react-devtools/extension
Use it in your browser to check for unnecessary renders.

VS Code Extensions:

ESLint: Ensures clean and optimized code.
Prettier: Enforces consistent code formatting.
Code Time: Tracks your coding habits and focuses on slow parts.

  1. Optimize Rendering Use React.memo: Wrap functional components with React.memo to avoid unnecessary re-renders.

jsx
Copy code
import React, { memo } from 'react';

const MyComponent = memo(({ prop }) => {
console.log('Rendering MyComponent');
return

{prop};
});

export default MyComponent;
Use useCallback and useMemo: Prevent new function instances on every render.

jsx
Copy code
import React, { useState, useCallback, useMemo } from 'react';

const App = () => {
const [count, setCount] = useState(0);

const expensiveComputation = useMemo(() => {
console.log('Expensive computation');
return count * 2;
}, [count]);

const handleClick = useCallback(() => {
setCount((prev) => prev + 1);
}, []);

return (


Count: {count}


Double: {expensiveComputation}


Increment

);
};

export default App;

  1. Minimize State Re-renders Lift State Up: Share state only where necessary. Avoid Props Drilling: Use Context API or state management tools like Redux or Zustand
npm install zustand

Enter fullscreen mode Exit fullscreen mode

Example with Zustand:

import create from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}));

const Counter = () => {
  const { count, increment } = useStore();
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

export default Counter;

Enter fullscreen mode Exit fullscreen mode
  1. Code Splitting and Lazy Loading Reduce the initial load time by splitting code and lazily loading components:
import React, { Suspense, lazy } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

const App = () => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode
  1. Use the Right Build Tools Use ESBuild or SWC for faster builds:
npm install -D esbuild

Enter fullscreen mode Exit fullscreen mode

Switch to Vite for a faster development server

npm create vite@latest

Enter fullscreen mode Exit fullscreen mode

If you feel that React is slow in your project, there are several steps you can take to optimize its performance. Here's a practical guide with changes in your VS Code setup, tools, and coding techniques:

  1. Analyze and Monitor Performance Use tools to find bottlenecks:

React DevTools: Inspect your component hierarchy and identify re-render issues.

bash
Copy code
npm install --save-dev @react-devtools/extension
Use it in your browser to check for unnecessary renders.

VS Code Extensions:

ESLint: Ensures clean and optimized code.
Prettier: Enforces consistent code formatting.
Code Time: Tracks your coding habits and focuses on slow parts.

  1. Optimize Rendering Use React.memo: Wrap functional components with React.memo to avoid unnecessary re-renders.

jsx
Copy code
import React, { memo } from 'react';

const MyComponent = memo(({ prop }) => {
console.log('Rendering MyComponent');
return

{prop};
});

export default MyComponent;
Use useCallback and useMemo: Prevent new function instances on every render.

jsx
Copy code
import React, { useState, useCallback, useMemo } from 'react';

const App = () => {
const [count, setCount] = useState(0);

const expensiveComputation = useMemo(() => {
console.log('Expensive computation');
return count * 2;
}, [count]);

const handleClick = useCallback(() => {
setCount((prev) => prev + 1);
}, []);

return (


Count: {count}


Double: {expensiveComputation}


Increment

);
};

export default App;

  1. Minimize State Re-renders Lift State Up: Share state only where necessary. Avoid Props Drilling: Use Context API or state management tools like Redux or Zustand. bash Copy code npm install zustand Example with Zustand: jsx Copy code import create from 'zustand';

const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}));

const Counter = () => {
const { count, increment } = useStore();
return (


Count: {count}


Increment

);
};

export default Counter;

  1. Code Splitting and Lazy Loading Reduce the initial load time by splitting code and lazily loading components:

jsx
Copy code
import React, { Suspense, lazy } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

const App = () => {
return (
Loading...}>


);
};

export default App;

  1. Use the Right Build Tools Use ESBuild or SWC for faster builds: bash Copy code npm install -D esbuild Switch to Vite for a faster development server: bash Copy code npm create vite@latest
  2. Audit Your Dependencies Use tools like npm analyze to identify large libraries
npm install -g source-map-explorer
source-map-explorer build/static/js/*.js

Enter fullscreen mode Exit fullscreen mode

Replace heavy libraries with lightweight alternatives:
Replace Lodash with native JS or smaller utility libraries like remeda.
Use date-fns instead of moment.

  1. Improving VS Code Performance Install extensions for linting and performance suggestions: Auto Import: Saves time managing imports. React Pure Components: Highlights components that can be optimized. Adjust VS Code settings: json Copy code
"editor.quickSuggestions": { "other": true },
"files.autoSave": "onFocusChange",
"editor.formatOnSave": true,
"typescript.tsserver.experimental.enableProjectDiagnostics": true

Enter fullscreen mode Exit fullscreen mode
  1. Optimize Images and Assets Use Next.js Image Optimization or libraries like react-image for lazy-loaded images. Compress assets
npm install imagemin-cli
imagemin src/assets/* --out-dir=dist/assets

Enter fullscreen mode Exit fullscreen mode
  1. Switch to Alternatives If React doesn't meet your performance needs, explore alternatives:

Solid.js: Smaller and faster than React.
Svelte: Optimizes components at compile time.

Top comments (5)

Collapse
 
baby123345 profile image
qwaszx

Great breakdown of React optimization techniques! Which performance tool do you find most effective for identifying bottlenecks?

Collapse
 
nihal00009 profile image
Comment deleted

Some comments may only be visible to logged-in visitors. Sign in to view all comments.