Skip to main content

7.15 Optimization Functional Components With React.memo

functional react.memo = class-based shouldComponentUpdate

Cockpit.js
...

const assignedClasses = [];
let btnClass = "";
if (props.showPersons) btnClass = classes.Red;
if (props.personsLength <= 2) {
assignedClasses.push(classes.red); // classes = ['red']
}
if (props.personsLength <= 1) {
assignedClasses.push(classes.bold); // classes = ['red', 'bold']
}
return (
<div className={classes.Cockpit}>
<h1>{props.title}</h1>
<p className={assignedClasses.join(" ")}>This is really working!</p>
<button className={btnClass} onClick={props.clicked}>
Toggle Persons
</button>
</div>
);
};

export default React.memo(cockpit);
App.js
...

return (
<div className={classes.App}>
<button
onClick={() => {
this.setState({ showCockpit: !this.state.showCockpit });
}}
>
Remove Cockpit
</button>
{this.state.showCockpit ? (
<Cockpit
title={this.props.appTitle}
personsLength={this.state.persons.length}
showPersons={this.state.showPersons}
clicked={this.togglePersonsHandler}
/>
) : null}
{persons}
</div>
);
}
}

export default App;