I've been playing around with React 16.6.0
recently and I love the idea of React Memo, but I've been unable to find anything regarding scenarios best suited to implement it.
The React docs (https://reactjs.org/docs/react-api.html#reactmemo) don't seem to suggest any implications from just throwing it on all of your functional components.
Because it does a shallow comparison to figure out if it needs to re-render, is there ever going to be a situation that negatively impacts performance?
A situation like this seems like an obvious choice for implementation:
// NameComponent.js
import React from "react";
const NameComponent = ({ name }) => <div>{name}</div>;
export default React.memo(NameComponent);
// CountComponent.js
import React from "react";
const CountComponent = ({ count }) => <div>{count}</div>;
export default CountComponent;
// App.js
import React from "react";
import NameComponent from "./NameComponent";
import CountComponent from "./CountComponent";
class App extends Component {
state = {
name: "Keith",
count: 0
};
handleClick = e => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<NameComponent name={this.state.name} />
<CountComponent count={this.state.count} />
<button onClick={this.handleClick}>Add Count</button>
</div>
);
}
}
Because name
will never change in this context, it makes sense to memoize.
But what about a situation where props change frequently?
What if I added another button that changed something else in state and triggered a re-render, would it make sense to wrap CountComponent
in memo, even though this component by design is meant to update frequently?
I guess my main question is as long as everything remains pure, is there ever a situation to not wrap a functional component with React Memo?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…