This is more of a React performance question.
My question would be, adding/removing a CSS classname (I.e. Adding "show" class name) to an element is better via DOM manipulation or state change? I do find that direct DOM manipulation "classList" is definitely faster when the targeted DOM element is already known.
A snippet would be:
const menuRef= React.createRef();
constructor(props) {
super(props);
/*if I am to use state*/
//this.state = {isMenuShown: false}
}
_toggleShow = () => {
//Changing states?
/* this.setState({isMenuShown: !this.state.isMenuShown}); */
if(this.menuRef.current) {
if(!this.menuRef.current.classList.contains("show")) {
this.menuRef.current.classList.add("show");
}
else {
this.menuRef.current.classList.remove("show");
}
}
}
render() {
let ulClassName = "";
/* If I am to use state*/
//ulClassName = this.state.isMenuShown ? "show":"";
return (
<React.Fragment>
<nav onClick={this._toggleShow)>
<ul ref={this.menuRef} className={ulClassName}>
<li>Sample 1</li>
<li>Sample 2</li>
</ul>
</nav>
<style jsx>{`
ul {
display: none;
}
ul.show {
display: block;
//I can add CSS @keyframes to display
//Inner child elements relies on ".show" too for responsive design.
}
`}</style>
</React.Fragment>
);
}
I know that states are the advised way to go, but scenario above justifies(at least to me) that DOM manipulation is better when CSS are heavily relied on. Take example for the CSS usage are:
- Inner child responsive designs.
- Animation using CSS @keyframes
What would you really use or how does one over come this? In future did DOM manipulation actually create a problem for anyone?