Ali Akbar Azizi
Ali Akbar Azizi

Reputation: 3496

React memo with stateless component

Before react introduce memo and hook All functional component was stateless.

After Introducing memo and hook I'm little confused with these two concept.

Is React.memo for functions that use hook only?

Should I update all my stateless functional component to React.memo for optimizing? Or react optimize it when a function does not use hook automatically?

Upvotes: 0

Views: 1112

Answers (1)

Vandesh
Vandesh

Reputation: 6894

For understanding what React.memo is used for, first you have to understand the difference between React.Component and React.PureComponent.

From the docs -

The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

React.memo is the same as a React.PureComponent, just for the functional components. So, if you think that with a given props, your component will be rendered the same, you can wrap your component with React.memo for performance boost and memoizing the result as mentioned in the docs.

But do specifically take a look at the line in the docs, which says -

This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.

And you should make your decision about using React.memo irrespective of the hooks.

Upvotes: 1

Related Questions