DEV Community

Rohan Bagchi
Rohan Bagchi

Posted on • Originally published at rohanbagchi.hashnode.dev

Using React.memo

Using React.memo

PureComponent is a decent approach for performance optimisation as long as it is not prematurely opted in. It’s functional counterpart, memo is used these days with functional components.

Now there could be 2 ways to declare a component as a memoized one that I can think of:

Inline

import { memo } from 'react'

export const MyAwesomeFormWithInlineMemo = memo(() => (
  <form>
    <label>
      Hey

      <input type="text" />
    </label>
  </form>
))
Enter fullscreen mode Exit fullscreen mode

Not Inline (do not know what to call this approach):

import { memo } from 'react'

const MyAwesomeForm = () => (
  <form>
    <label>
      Yo!

      <input type="text" />
    </label>
  </form>
);

export const MemoedMyAwesomeForm = memo(MyAwesomeForm);
Enter fullscreen mode Exit fullscreen mode

Now while both will have similar behaviour, the 2nd approach provides better DX in browser devtools.

Lets look at how these look in the components tab in devtools:

Component definition + usage

Devtools view

This is because memo is an HOC which does not attach a readable displayName to the returned component. This gets worse as we add on more inline memo components as children to it.

export const MyAwesomeFormWithInlineMemoX = memo(() => (
  <div style={{ padding: 20 }}>
    <fieldset>
      <MyAwesomeFormWithInlineMemo />
    </fieldset>
  </div>
));
Enter fullscreen mode Exit fullscreen mode

This is how the inner memo’ed component ends up looking in devtools

As such, while the inline approach works, it adds friction to maintenance.

The 2nd approach however is wrapping over a component MyAwesomeForm that already has an implicit name. React is now able to set the displayName correctly and it shows up in the devtools as expected.

Suggestion

Please use the second approach if possible. Create a component and then export it using memo. This allows us to find components in devtools and map it to their source code for easier maintainability :)

If we must use the inline approach, please assist memo by defining a named function inside:

import { memo } from 'react'

export const AwesomeComponent = memo(function AwesomeComponent() {
  return ...;
});
Enter fullscreen mode Exit fullscreen mode

^ This will show up as AwesomeComponent in devtools same way

Top comments (0)