I'm having trouble deciding the difference between these two patterns of rendering in React. Hopefully someone can shed some light on this matter.
Pattern 1: React's Conditional Render
.html
class List extends React.Component {
state = {
menu: false,
}
handleMouseOver = () => {
this.setState({
menu: true
});
}
handleMouseLeave = () => {
this.setState({
menu: false
});
}
render() {
const { menu } = this.state;
return (
<li
onMouseOver={this.handleMouseOver}
onMouseLeave={this.handleMouseLeave}
>
{menu && <Menu />}
</li>
);
}
}
Pattern 2: display: none
.menu {
display: none;
}
.li:hover .menu {
display: block;
}
const List = () => (
<li className="li"><Menu className="menu"/></li>
);
Question:
If I need to render 100 of these items in a single page, which pattern should I go for?
How can I determine which pattern is better?
Are there any performance benefit of using one over the other?
I'm having trouble deciding the difference between these two patterns of rendering in React. Hopefully someone can shed some light on this matter.
Pattern 1: React's Conditional Render
https://facebook.github.io/react/docs/conditional-rendering.html
class List extends React.Component {
state = {
menu: false,
}
handleMouseOver = () => {
this.setState({
menu: true
});
}
handleMouseLeave = () => {
this.setState({
menu: false
});
}
render() {
const { menu } = this.state;
return (
<li
onMouseOver={this.handleMouseOver}
onMouseLeave={this.handleMouseLeave}
>
{menu && <Menu />}
</li>
);
}
}
Pattern 2: display: none
.menu {
display: none;
}
.li:hover .menu {
display: block;
}
const List = () => (
<li className="li"><Menu className="menu"/></li>
);
Question:
If I need to render 100 of these items in a single page, which pattern should I go for?
How can I determine which pattern is better?
Are there any performance benefit of using one over the other?
Share Improve this question asked Mar 29, 2017 at 12:52 cusXcusX 5002 gold badges7 silver badges17 bronze badges1 Answer
Reset to default 15I tend to use display: none
in situations where there's a simple condition to show something (e.g hover, etc).
If it's a bit more complex (e.g. click a checkbox to hide an element) then I go with conditional rendering.
The reason behind this is that I don't want to cause state changes and trigger an update for something as trivial as a hover state, and don't want to fiddle around with obscure css classes for things that will have to involve code anyway.
Again, this is my personal preference.
TL;DR: CSS if super simple (e.g. hover), conditional render if more logic involved