How do I prevent my memoized React component from showing as "Anonymous" in React DevTools?

Viewed 344

When defining a React component with React.memo like

const MyComponent = React.memo((props) => <div>...</div>);

the React DevTools label the component "Anonymous" in the component tree. This can make debugging confusing if the application contains multiple memoized components.

How can I make my memoized component's name show up in the React DevTools?

2 Answers

Anonymous is the fallback name that is displayed if the function has no intrinsic .name or user-supplied .displayName. Generally this means it was declared as an anonymous inline function, e.g. React.memo(props => ...).

To show the component's name you should pass the component like this

const MyComponent = props => <div>...</div>;

export default React.memo(MyComponent);

Set the displayName property of the component to fix this:

const MyComponent = React.memo((props) => <div>...</div>);

MyComponent.displayName = 'MyComponent'
Related