DEV Community

Qasem Nik
Qasem Nik

Posted on

3 1

10 Quick Wins for a Faster React App

🌟 Optimizing your React application for performance doesn’t have to be a daunting task. Here are 10 quick wins you can implement to ensure your React app runs faster and smoother. Each tip is accompanied by practical examples and code snippets. ✨🚀


1. Use React.PureComponent

React.PureComponent automatically performs a shallow comparison of props and state to prevent unnecessary re-renders. 🔍⚡️💡

Example:

import React from 'react';

class PureChild extends React.PureComponent {
  render() {
    console.log('Rendered PureChild');
    return <div>{this.props.text}</div>;
  }
}

function App() {
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <PureChild text="Hello, World!" />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

2. Defer Non-Critical Assets

Load assets like images or videos lazily to improve initial load time. 📸⏳🛠

Example:

import React, { Suspense } from 'react';

const LazyImage = React.lazy(() => import('./ImageComponent'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyImage src="large-image.jpg" alt="Lazy Loaded" />
    </Suspense>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

3. Use React.memo for Functional Components

Prevent re-renders of functional components by wrapping them with React.memo. 🧠⚙️💻

Example:

import React from 'react';

const MemoizedComponent = React.memo(({ value }) => {
  console.log('Rendered MemoizedComponent');
  return <div>{value}</div>;
});

function App() {
  const [state, setState] = React.useState(0);

  return (
    <div>
      <button onClick={() => setState(state + 1)}>Update State</button>
      <MemoizedComponent value="Static Value" />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

4. Implement Code Splitting

Reduce initial load time by splitting your code into smaller bundles using dynamic imports. 📦⚡️✨

Example:

import React, { Suspense } from 'react';

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode

5. Optimize Images

Use optimized image formats like WebP and leverage tools like Cloudinary or Imgix for on-the-fly image optimization. 🖼🚀📲

Example:

<img src="https://example.com/image.jpg?auto=format&fit=max&w=500" alt="Optimized" />
Enter fullscreen mode Exit fullscreen mode

6. Use a Service Worker

Cache assets and API responses using service workers for faster subsequent loads. 🔧📂⚡️

Example:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(() => console.log('Service Worker Registered'))
    .catch((error) => console.log('Service Worker Registration Failed', error));
}
Enter fullscreen mode Exit fullscreen mode

7. Use useMemo and useCallback Hooks

Memoize expensive calculations or functions to avoid re-computation on every render. 🧮🛠📈

Example:

import React from 'react';

function App() {
  const [count, setCount] = React.useState(0);

  const expensiveCalculation = React.useMemo(() => {
    console.log('Calculating...');
    return count * 2;
  }, [count]);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <div>Result: {expensiveCalculation}</div>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

8. Avoid Anonymous Functions in JSX

Anonymous functions in JSX create new instances on every render, leading to potential performance issues. 🚫🔄🔧

Example:

function App() {
  const [count, setCount] = React.useState(0);

  const increment = () => setCount(count + 1);

  return (
    <div>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

9. Use Virtualized Lists

For rendering long lists, use libraries like react-window or react-virtualized to only render visible items. 📜⚡️🖥

Example:

import React from 'react';
import { FixedSizeList as List } from 'react-window';

function Row({ index, style }) {
  return <div style={style}>Row {index}</div>;
}

function App() {
  return (
    <List height={150} itemCount={1000} itemSize={35} width={300}>
      {Row}
    </List>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

10. Leverage react-query for Data Fetching

react-query efficiently manages server-state and caching, reducing unnecessary network requests. 🔄🌐📉

Example:

import { useQuery } from 'react-query';

function fetchData() {
  return fetch('https://api.example.com/data').then((res) => res.json());
}

function App() {
  const { data, isLoading } = useQuery('fetchData', fetchData);

  if (isLoading) return <div>Loading...</div>;

  return <div>{JSON.stringify(data)}</div>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

🚀 By implementing these quick wins, you’ll ensure your React app is not only fast but also scalable and user-friendly. Start with these tips and watch your app’s performance soar! 🌟🔥

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (1)

Collapse
 
muzammilali_11 profile image
Muzammil Ali

This post has some worth while reading

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more