Points to note to improve the performance of react app – part 1

Tram Ho

React itself has used techniques to optimize the UI rendering process, but depending on the complexity and business of the app, React itself cannot adequately optimize the rendering process; So we need to implement techniques to improve the performance of the app.

Use shouldComponentUpdate

Usually child components always re-render according to the parent component even though the props passed to these child components have not changed.

In fact, we only need to render the child components only when the props passed change, to do this we need to implement the shouldComponentUpdate function like so:

In most cases, instead of implementing the shouldComponentUpdate manual function, it is possible to inherit a component class from PureComponent instead of Component .

PureComponent similar to shouldComponentUpdate with the shallow comparison of props, state

Similar to PureComponent in class component, we can use React.memo in functional component as follows:

Using useMemo, useCallback hooks in a functional component

If the app has data that needs complex computation, we need to cached (memorized) these data so that we don’t have to recalculate if the input doesn’t change.

useMemo

useMemo only perform computeExpensiveValue if a or b changes.

We can also apply useMemo to cached a react component like this:

useCallback

useMemo is used to cached value, while useCallback used to cached a callback function

So we can use useCallback to cached a funtion callback doesn’t change reference in every render.

Virtualize Long Lists

This is a performance optimization technique if rendering a long, complex data list. This technique only renders a group of items in the list on the UI rather than rendering the entire list data

There are many libs supporting this technique, typically react-window and react-virtualized , which provide components for displaying list, grid, table.

Use a Production Build

When we release a react app we need to build in production mode, this ensures the react version gets rid of unnecessary warnings, debug code, components, tools support while dev, and reduces build size, etc.

Use the build file:

webpack:

Conclude

Above are some points to note to improve the performance of the react app, some more techniques will be in the next part, please read it, thank you!

Share the news now

Source : Viblo