0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

before these release I use stateless function for optimizing instead of Purecomponent because component’s render() function renders the same result given the same props. And If React.memo use for prevent re-render, So in the past PureComponent was better that function component?
Better - subjective. Useful in situations where a component renders the same with the same props - yes, as it's more performant.
Why not better? Purecomponent doest not re-render, and functional compoenent before this release should re-render if props changes. so in this scenario in the past should I use PureComponent? because there is no memo
As I said, better is subjective because of the line in the documentation - "This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs." In your case, if you use it as a way to prevent render, it can introduce bugs.
If you consider the optimization bit, then yes, again - only in the conditon where the render is same with the same props. So, just to make that optimization available with the functional components, React.memo was introduced. I love this post which has an elaborate discussion - stackoverflow.com/questions/40703675/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.