Skip to main content

React Performance

Introduction

Approaches to improving performance in React can be divided to 4 categories:

  1. Structure Components & Application
  2. Caching and Memoization of Components - skip doing stuff if you can
  3. Suspense API (lazy loading) - put off doing stuff
  4. React Concurrency Features - do urgent first, rest later

If you want to improve performance

  1. Put memos into places, identify and reduce rerenders
  2. Start breaking app into chunks, use suspense

But first check if your app is on a CDN, there might be more crucial and effective fixes there. Get infrastructure in place first.

React Rendering Cycle

  1. Render Phase - After a change, React calculates the diff and figures best heuristics to update the DOM
  2. Commit Phase - updates the DOM and refs, the useEffect runs end of here
  3. Cleanup Phase

Rerenders are triggered by: State Changes When a parent component changes, all children will rerender.

Reconcilliation is the process of comparing the virtual DOM with the real DOM to figure out what needs to be changed.

Caching and Memoization of Components

React.memo() => memoizes the component, if the props are the same, it will not rerender.

React.useMemo() => memoizes the value, if the dependencies are the same, it will not rerender.

React.useCallback() => memoizes the function, if the dependencies are the same, it will not rerender.

Suspense API (lazy loading)

React.lazy() => lazy loads the component, if the component is not needed, it will not be loaded.

Break application into bundles, and send them piece by piece. Basically, download components when you need them, instead of initiation.

const Component = lazy(() => import("./Component"));

<Suspense fallback={<Loading />}>
<Component />
</Suspense>;

Conclusion

  1. Solve component hierarchy & state
  2. Memoization is good if cost of its checks are worth it
  3. Suspense API is a good idea
  4. Use transition API if you need it
  5. Use React Profiler to find bottlenecks