DEV Community

Qasem Nik
Qasem Nik

Posted on

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! ๐ŸŒŸ๐Ÿ”ฅ

Top comments (1)

Collapse
 
muzammilali_11 profile image
Muzammil Ali

This post has some worth while reading