Users enjoy fast and responsive user interfaces (UI). A UI response delay of fewer than 100 milliseconds feels instant to the user but a delay between 100 and 300 milliseconds is already perceptible.
To improve user interface performance, React offers a higher-order component
React.memo()
. When React.memo()
wraps a component, React memoizes the rendered output of the wrapped component then skips unnecessary renderings.- Not to be confused with a private placement memorandum or credit memo, a memo letter is a type of business letter used mostly for internal communication within a company, organization, or school.
- Memo definition is - a usually brief written message or report: memorandum. How to use memo in a sentence.
This post describes the situations when
React.memo()
improves the performance, and, not less important, warns when its usage is useless.Memo Restaurant
A memo is one of the most important forms of communication used in public and private organizations. When communicating with colleagues and other internal stakeholders through a memorandum, it is important to use the proper format. Understanding the correct memo format can help you communicate information more efficiently and professionally. Title Memo # Posting Date Fiscal Year; April and July 2011 Changes to Nursing Home Compare: 11-17-NH: 2011-03-18: 2011: Clarification of Self-Administration of Medications.
Plus I’ll describe some useful memoization tips you should be aware of.
1. React.memo()
When deciding to update DOM, React first renders your component, then compares the result with the previous render. If the render results are different, React updates the DOM.
Current vs previous render results comparison is fast. But you can speed up the process under some circumstances.
When a component is wrapped in
React.memo()
, React renders the component and memoizes the result. Before the next render, if the new props are the same, React reuses the memoized result skipping the next rendering.Let’s see the memoization in action. The functional component
Movie
is wrapped in React.memo()
:React.memo(Movie)
returns a new memoized component MemoizedMovie
.MemoizedMovie
outputs the same content as the original Movie
component, but with one difference — MemoizedMovie
render is memoized. React reuses the memoized content as long as title
and releaseDate
props are the same between renderings:Open the demo, then expand the console. You will see that React renders
<MemoizedMovie>
just once, while <Movie>
re-renders every time.You gain a performance boost: by reusing the memoized content, React skips rendering the component and doesn’t perform a virtual DOM difference check.
The same functionality for class components is implemented by PureComponent.
1.1 Custom equality check of props
By default
React.memo()
does a shallow comparison of props and objects of props.To customize the props comparison you can use the second argument to indicate an equality check function:
areEqual(prevProps, nextProps)
function must return true
if prevProps
and nextProps
are equal.For example, let’s manually calculate if
Movie
component props are equal:moviePropsAreEqual()
function returns true
if prev and next props are equal.2. When to use React.memo()
2.1 Component renders often with the same props
The best case of wrapping a component in
React.memo()
is when you expect the functional component to render often and usually with the same props.A common situation that makes a component render with the same props is being forced to render by a parent component.
Let’s reuse
Movie
component defined above. A new parent component MovieViewsRealtime
displays the number of views of a movie, with realtime updates:The application regularly polls the server in the background (every second), updating
views
property of MovieViewsRealtime
component.Every time
views
prop is updated with a new number, MovieViewsRealtime
renders. This triggers Movie
rendering too, even if title
and releaseDate
remain the same.That’s the right case to apply memoization on
Movie
component.Let’s use the memoized component
MemoizedMovie
inside MovieViewsRealtime
to prevent useless re-renderings:As long as
title
and releaseDate
props are the same, React skips rendering MemoizedMovie
. This improves the performance of MovieViewsRealtime
component.The more often the component renders with the same props, the heavier and the more computationally expensive the output is, the more chances are that component needs to be wrapped in
React.memo()
.Anyways, use profiling to measure the benefits of applying
React.memo()
.3. When to avoid React.memo()
If the component isn’t heavy and usually renders with different props, most likely you don’t need
React.memo()
.Use the following rule of thumb: don’t use memoization if you can’t quantify the performance gains.
Lg tv mirror app for iphone. Performance-related changes applied incorrectly can even harm performance. Use
React.memo()
wisely.While possible, wrapping class-based components in
React.memo()
is undesirable. Extend PureComponent
class or define a custom implementation of shouldComponentUpdate()
method if you need memoization for class-based components.3.1 Useless props comparison
Imagine a component that usually renders with different props. In this case, memoization doesn’t provide benefits.
Even if you wrap such a volatile component in
React.memo()
, React does 2 jobs on every rendering:- Invokes the comparison function to determine whether the previous and next props are equal
- Because props comparison almost always returns
false
, React performs the diff of previous and current render results
You gain no performance benefits but also run for naught the comparison function.
4. React.memo() and callback functions
The function object equals only to itself. Let’s see that by comparing some functions:
sumFactory()
is a factory function. It returns functions that sum 2 numbers.Memo Report Format
The functions
sum1
and sum2
are created by the factory. Both functions sum numbers. However, sum1
and sum2
are different function objects (sum1 sum2
is false
).Every time a parent component defines a callback for its child, it creates new function instances. Let’s see how this breaks memoization, and how to fix it.
The following component
Logout
accepts a callback prop onLogout
:A component that accepts a callback must be handled with care when applying memoization. The parent component could provide different instances of the callback function on every render:
Memo Report
Even if provided with the same
username
value, MemoizedLogout
renders every time because it receives new instances of onLogout
callback.Memoization is broken.
To fix it,
onLogout
prop must receive the same callback instance. Let’s apply useCallback() to preserve the callback instance between renderings:useCallback(() => cookies.clear('session'), [cookies])
always returns the same function instance as long as cookies
is the same. Memoization of MemoizedLogout
is fixed.Flower Design Images Flower Pattern Design Flower Patterns Flower Designs Embroidery Flowers Pattern Embroidery Patterns Free Hand Embroidery Designs Pattern Sketch Pattern Drawing. Latest embroidery flowers designs patterns drawings and sketches on tracing paper 2020. Drawing & Illustration Mixed Media & Collage Fiber Arts. Rare 500 Designs HAND EMBROIDERY PATTERNS Book for Crafting Beginners and Experts This Printable Pdf book is an Instant Digital Download CraftingBooks 5 out of 5 stars (10) Sale Price. Feb 3, 2021 - Explore Mahima Aggarwal's board 'Hand Embroidery Patterns', followed by 481 people on Pinterest. See more ideas about embroidery patterns, hand embroidery, embroidery. All the best Embroidery Designs Sketch 39+ collected on this page. Feel free to explore, study and enjoy paintings with PaintingValley.com. Hand embroidery designs sketches.
5. React.memo() is a performance hint
Strictly, React uses memoization as a performance hint.
While in most situations React avoids rendering a memoized component, you shouldn’t count on that to prevent rendering.
6. React.memo() and hooks
Components using hooks can be freely wrapped in
React.memo()
to achieve memoization.React always re-renders the component if the state changes, even if the component is wrapped in
React.memo()
.7. Conclusion
React.memo()
is a great tool to memoize functional components. When applied correctly, it prevents useless re-renderings when the next props equal to previous ones.Take precautions when memoizing components that use props as callbacks. Make sure to provide the same callback function instance between renderings.
Don’t forget to use profiling to measure the performance gains of memoization.
What to read next? To memoize callbacks in React I recommend checking my post Your Guide to React.useCallback().
Do you know interesting use cases of React.memo()? If so, please write a comment below!
Like the post? Please share!
Memo Remigi
Quality posts into your inbox
I regularly publish posts containing:
- Important JavaScript concepts explained in simple words
- Overview of new JavaScript features
- How to use TypeScript and typing
- Software design and good coding practices
Subscribe to my newsletter to get them right into your inbox.
About Dmitri Pavlutin
Software developer, tech writer and coach. My daily routine consists of (but not limited to) drinking coffee, coding, writing, coaching, overcoming boredom ?.
1.8K followers