Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Is manual memoization necessary?

Tags:

reactjs

Reading through React - Basic Theoretical Concepts and the upcoming React Fiber Architecture, it seems memoization plays an important central part in the React data handling logic along with immutable data stores.
However, what is not immediately obvious is whether and to what extent is memoization handled internally by React and if and when should a developer memoize manually?

Shortly put, when does React internally memoize function calls and when should a developer do so themselves? Does React memoize any non-internal function calls automatically at all?

like image 603
Etheryte Avatar asked Aug 16 '16 11:08

Etheryte


People also ask

Should I memoize everything React?

memo() everything makes React more efficient, it should be a default behavior, not only an optional (like pure function). For shorter explanation: React. memo() prevents some redundant rerender by comparing the component's previous and current props.

Should you always use memo in React?

The first and the most obvious case where we should avoid using React. memo() is when we cannot possibly quantify the performance gains from it. If the computational time of our component's re-render — with and without this higher-order component is negligible or non-existent, then using React. memo() would be useless.

What is the role of memoization in React?

Memoization is an optimization feature in React which, when used in the right place, increases the performance of the program. React gives us PureComponent and memo to implement memoization. PureComponent is used with the class component and memo is used with the function component.

Are React hooks memoized?

The React useMemo Hook returns a memoized value. Think of memoization as caching a value so that it does not need to be recalculated. The useMemo Hook only runs when one of its dependencies update. This can improve performance.


1 Answers

React will not do the kind of memoization show in your example, React - Basic Theoretical Concepts. That is up to you.

The best place to do memoization is when you are building your components props. Ie if you have state -> props -> components. You can memoize the mapping from state to props.

If you need the performance gains you get with memoization, and you are thinking of using redux, the reselect docs are a good place to start.

If you go down this road, another large performance gain will come if you also do shallow prop checking in your shouldComponentUpdate function.

like image 176
Eoin Avatar answered Oct 18 '22 06:10

Eoin