9 must-know performance optimization tips for React.js

1. useState Lazy Initialization With Function

There are times when we need to set the initial value of the state from some variable or from a function that returns a value.

Since our function is in the body, every time a re-render happens, this function is getting called even if its value is not required (we only need it during the initial render).

2. Monitor Unnecessary Renders in Your Applications

One of the common problems we face is evaluating the necessary renders in your application that are having a bad impact on the performance.

There are different ways we can evaluate them to avoid unnecessary renders in minutes. Use why-did-you-render package to do a post-mortem of the app.

3. Using React.memo and useMemo

React.memo does a shallow comparison out of the box and avoids rendering. Memoizing the result will provide a performance boost. This means that React will skip rendering the component and reuse the last rendered result.

Read more about react.memo

4. Deep Comparison in shouldComponentUpdate

Use deep-equal to compare two objects and return whether they are equal according to a recursive equality algorithm.

5. React Window

When the list grows long, it’s like poison is slowly entering your application and having a bad impact on the performance. It starts consuming a lot of memory in the browser. Since all the list items are in the DOM, there is a lag when you scroll the list. Make use of react-window.

6. React Query

With hooks for fetching, caching, and updating asynchronous data in React, managing server state is easier than ever before with React Query.

Some of the benefits of using react-query

- Transport/protocol/back-end agnostic data fetching (REST, GraphQL, promises, whatever!)

- Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)

- Parallel + Dependent Queries

- Mutations + Reactive Query Refetching

- Paginated + Cursor-based Queries

- Load-More + Infinite Scroll Queries w/ Scroll Recovery

- Request Cancellation

read more about react-query.

7. One Function to Update Multiple Input State Values

This is the common use case of keeping the same function to update multiple input values. Most of us know about this approach that helps to reduce the code and get our job done.

8. Making Use of Custom Hooks

With hooks, we don’t have some facility that can help us get the callback as in the case of setState. Make use of custom hooks to reduce the code.

For more easy-to-understand hook recipes, try useHooks

9. Lazy Loading React Components

Lazy loading is the technique of rendering only needed or critical user interface items first, then quietly unrolling the non-critical items later. The React.lazy function lets you render a dynamic import as a regular component.

10. [ Bonus ] Pause Console Debugger

Freeze dropdown in browser to inspect it properly

This is a lifesaver tip.

 

credits to Harsh Makadia