As far as my React experience has taken me so far, I have two methods of hiding some rendered HTML from a React components output/render based on props/state:
I wonder which is best practice? I have a hunch that there may be some performance gain by using the CSS method as the browser doesn't need to manipulate the DOM as heavily. Alternatively, it's sometimes nice to have an element completely removed from the DOM.
Any insights?
I asked a similar question here and received a reply from Sophie Alpert, one of the members of React core team.
Basically in most cases it's better not to render the HTML at all if it should stay that way throughout the lifetime of that page. If frequent toggling is desired, then use CSS to show/hide the element.
From performance perspective: react intelligently minimizes DOM re-renders, including special treatment if you change a list of items (eg <li>
items) in the DOM. And react is really fast. Haven't tested, but I would think any difference in performance would be minimal.
If the component in question is pure HTML, then I generally apply the following rule of thumb between the 2 ways of hiding elements:
NB: For components that hold more than just HTML, eg components containing input fields or buttons, or for react components, it is better to let react remove them from the DOM. To let react also nicely clean up possible event listeners etc etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.