Optimizing Performance in React
Performance Tools in React
React-addons-perf
The Perf methods can be used to take performance measurements.
Perf.printInclusive()
prints overall time taken.Perf.printExclusive()
prints time excluding mounting timePerf.printWasted()
prints time wasted on components that didn't actually render anything.Perf.printOperations()
prints all DOM manipulationsPerf.getLastMeasurements()
prints the measurement from the last Perf session.
Avoid Reconciliation
shouldComponentUpdate()
Here we use a shallow comparison to determine if the props of the component have changed. If so, the component should update.
React.PureComponent
This is a React component that implements shouldComponentUpdate()
and only diffs and updates when it returns true
. Any child of PureComponent
must also be a PureComponent
.
Other hooks
useReducer
This is an alternative to useState. Accepts a reducer of type (state, action) => newState
, and returns the current state paired with a dispatch
method.
Cases to use useReducer over useState:
Complex state logic that involves multiple sub-values
The next state depends on the previous one
Optimize performance for components that trigger deep updates by passing
dispatch
down instead of callbacks.
The dispatch
function identity is stable and won't change on re-renders.
useCallback
This returns a memoized callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate
).
useCallback(fn, deps)
is equivalent to useMemo(() => fn, deps).
Not Mutating Data
Code examples
Consider this example:
This example creates a bug and "world" is not actually displayed
To solve this problem, we should avoid mutating values that we are using as props or state.
One solution using concat
can be:
Or we can use the spread operator in ES6:
For objects, we can also write code to avoid mutating objects. This is the way in which we mutate an object:
However, we can avoid mutating the original object using Object.assign
in ES6:
Or, we can use the spread operator for objects from ES2018:
Immer
This is the basic syntax using Immer to avoid mutating data:
useState + Immer
Here is an example on CodeSandbox that uses the hook useState and Immer together.
useImmer
The state updaters have the same pattern, so they can be simplified to using the user-immer package.
useReducer and Redux + Immer
Similar to useState
, Immer also combines with useReducer
. And we have useImmerReducer
method from the use-immer package.
For Redux + Immer, refer to this doc of Redux Toolkit:
Other readings on immutable data
A few points to note from this article:
Avoid inline function definition in the
render
functionAvoid using index as key for map
Avoid using props in initial states
Avoid spreading props on DOM elements
Avoid async initialization in
componentWillMount()
Memoize React components
Last updated