Skip to content

Instantly share code, notes, and snippets.

@OluwatobilobaGp
Created April 19, 2023 15:19
Show Gist options
  • Save OluwatobilobaGp/55e2c107940f49b3ca01af45b34286e3 to your computer and use it in GitHub Desktop.
Save OluwatobilobaGp/55e2c107940f49b3ca01af45b34286e3 to your computer and use it in GitHub Desktop.
React Memo Example
<div id="root"></div>

React Memo Example

React.memo can help you control what components re-render. It's like a PureComponent in the Class syntax, only this is for function components.

A Pen by CodePen on CodePen.

License.

const ChildOne = React.memo(props => {
console.log("Rerendering Child One");
return(
<div className="box">
<h2>Hello! {props.name}</h2>
<p>This component won't re-render, check your console.</p>
</div>
)
});
const ChildTwo = (props) => {
console.log('Rerendering Child Two')
return (
<div className="box">
<h2>Hello! {props.name}</h2>
<p>This component will render re-render, check your console.</p>
</div>
)
}
class App extends React.Component {
state = {
value: 1,
name: "Chris"
};
handleClick = () => {
this.setState({
value: this.state.value + 1
});
};
render() {
return (
<React.Fragment>
<div className="box">
<div>{this.state.value}</div>
<button onClick={this.handleClick}>+</button>
</div>
<ChildOne name={this.state.name} />
<ChildTwo name={this.state.name} />
</React.Fragment>
);
}
}
ReactDOM.render(<App />,
document.getElementById("root"))
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.production.min.js"></script>
body {
height: 100vh;
margin: 0;
display: grid;
place-items: center;
}
.box {
width: 300px;
h1 {
font-size: 20px;
margin: 0 0 1rem 0;
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css" rel="stylesheet" />
@OluwatobilobaGp
Copy link
Author

I find it interesting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment