Optimizing React applications is crucial for better user experience. Here are proven techniques.

1. Memoization

React.memo

const ExpensiveComponent = React.memo(({ data }) => {
    return <div>{processData(data)}</div>;
}, (prevProps, nextProps) => {
    return prevProps.data.id === nextProps.data.id;
});

useMemo

const expensiveValue = useMemo(() => {
    return computeExpensiveValue(a, b);
}, [a, b]);

useCallback

const handleClick = useCallback(() => {
    doSomething(id);
}, [id]);

2. Code Splitting

React.lazy

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

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

3. Virtualization

import { FixedSizeList } from 'react-window';

function VirtualizedList({ items }) {
    return (
        <FixedSizeList
            height={600}
            itemCount={items.length}
            itemSize={50}
        >
            {({ index, style }) => (
                <div style={style}>{items[index]}</div>
            )}
        </FixedSizeList>
    );
}

4. Avoid Unnecessary Renders

// Bad: Creates new object on every render
<ChildComponent config={{ theme: 'dark' }} />

// Good: Use useMemo or constant
const config = useMemo(() => ({ theme: 'dark' }), []);
<ChildComponent config={config} />

Best Practices

  1. Memoize expensive computations
  2. Split code by routes
  3. Virtualize long lists
  4. Avoid inline functions/objects
  5. Use production builds

Conclusion

Optimize React apps for better performance! ⚡