React Performance Tips

Pranshu
2 min readSep 27, 2020

Basically, by default React doesn’t optimize unnecessary renders for us. So we need to code keeping that in mind that we are not causing unnecessary re-renders.

Points to Remember related to performance:-

  1. Pure Components or React.memo
  2. useMemo & useCallback
  3. Reconciliation
  4. Profiler
  5. Referential Inequality

# Pure Components or React.memo

Pure components are basically components that do the task of checking if the currentState != nextState or currentProps != nextProps the components will re-render. We can achieve this by using shouldComponentUpdate lifecycle method. This method allows you to prevent unnecessary updates by returning false. But if we are using PureComponent we dont need to use shouldComponentUpdate and it handles this check by default.

export default class MakeitPure extends React.PureComponent {}

For Hooks we have React.memo(Component, ) to memoize the component, It does the same thing and we can also provide the second argument (optional) with a function call where we can check for certain props and state changes only to prevent unnecessary updates.

export const MakeitPure = React.memo(() => {}, checkEqual)

# useMemo & useCallback

React hooks added useMemo & useCallback hooks which can be used to memoize value,callbacks. It makes sure the props that you are passing down from parent to child components do not cause re-render if the dependency array has not changed.

useMemo(() => fn, deps), useCallback(fn, deps)

UseCallback returns a memoized callback and only updates when dependency array changes

useMemo also only recompute the memoized values if we are changing the dependency array.

# Reconciliation

React’s reconciliation algorithms every time creates an updated version of virtual dom and compares it with the pre-updated one and updates only those elements which are changed.

What can cause issues with reconciliation???

  1. Not providing unique keys when we have an array of list elements also causes performance issues. Never use index for key as you might add/remove/reorder list of elements that you are rendering.

2. We also need to avoid using styles inline in react.

<div style = {{display: “block”}} />

As this will always create a new object which is inefficient for react’s diffing algorithm

# Profiler

React Profiler is your friend you can use react profiler just like the chrome performance dev tool.

Profiler can be used to optimize your React Application to check if any particular prop, the state change is causing unnecessary re-renders. Profiler provides us with FlameChart which is generated by profiling interaction with our react application. We can see there how much time the component took to render, why that component rendered etc

--

--

Pranshu
0 Followers

Javascript/React Enthusiast