DEV Community

Cover image for Optimizing React Performance With Memoization and Code Splitting
HexShift
HexShift

Posted on • Edited on

Optimizing React Performance With Memoization and Code Splitting

Optimizing React Performance With Memoization and Code Splitting

As your React application grows, so does the importance of performance optimization. In this article, we’ll explore two powerful strategies—memoization and code splitting—to make your apps faster and more efficient.

Why Performance Matters

Modern web apps can be complex and component-heavy. Without optimization, unnecessary re-renders and large bundle sizes can slow down your UI and negatively affect user experience. Let's fix that.

1. Using React.memo to Avoid Unnecessary Re-Renders

React.memo is a higher-order component that prevents re-renders if props haven't changed.


const ExpensiveComponent = React.memo(({ data }) => {
  console.log("Rendering ExpensiveComponent");
  return <div>{data}</div>;
});

By wrapping your component with React.memo, you save resources by avoiding unnecessary recalculations.

2. Memoizing Functions With useCallback

When you pass functions to child components, they often re-render because functions are recreated on every render. useCallback fixes that:


const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);

This ensures the same function reference is used unless dependencies change.

3. Memoizing Values With useMemo

Use useMemo to cache the result of expensive calculations:


const computedValue = useMemo(() => {
  return expensiveFunction(input);
}, [input]);

This is useful for data transformations or filtering that doesn't need to run on every render.

4. Code Splitting With React.lazy and Suspense

Code splitting breaks your bundle into smaller pieces, loading them on demand. This drastically improves initial load times.


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

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

This loads HeavyComponent only when needed, saving bandwidth and improving responsiveness.

Conclusion

React offers powerful built-in tools for performance optimization. Using memoization and code splitting can make a noticeable difference in user experience, especially in large-scale apps. Start identifying bottlenecks in your app and apply these strategies where they matter most.

For a much more extensive guide on getting the most out of React portals, check out my full 24-page PDF file on Gumroad. It's available for just $10:

Using React Portals Like a Pro.

If this post helped you, consider supporting me: buymeacoffee.com/hexshift

Top comments (0)