2

If I have a React component and I want to hide it. At the moment, I am taking two approaches:

The state management way

render() {
    return (
        <div>
            { this.state.showComponent && <Component/> }
        </div>
    );
}

The CSS way:

render() {
    return (
        <div>
            <Component className="hide-with-CSS"/>
        </div>
    );
}    

I assume that the former way will remove/add the component based on the current state while the latter way just "hides" it. So my questions are:

  • Which method would produce a better performance?
  • Is there another way to efficiently hide an element?
allicanseenow
  • 123
  • 1
  • 10
  • There's been posts about this already, e.g. https://stackoverflow.com/questions/24502898/show-or-hide-element-in-react – Jayce444 May 12 '18 at 06:08

2 Answers2

3

CSS solution will be faster for toggling between show and hide.

However, if this.state.showComponent is initially false, then the non-CSS way avoids mounting Component initially, so initial rendering will be faster.

Furthermore, when this.state.showComponent is false, the parent component will be more responsive to other events since it has one less component to render/re-render (when parent re-renders, Component gets re-rendered too even if its props didn't change, unless it's declared as pure or implemented shouldComponentUpdate).

The non-CSS approach is simpler as well since it doesn't involve CSS (whereas the CSS approach requires state management too to toggle the classname).

I'd therefore recommend the non-CSS approach.

Roy Wang
  • 11,112
  • 2
  • 21
  • 42
0

To hide or show element in both cases you will need to keep an update some state variable like showComponent and based on its value you got two options:

  • do a conditional rendering
  • toggle component CSS class

So the question is - what will work faster CSS or react mounting/unmounting mechanism?

Of course, CSS is going to be faster as it only changes the styling of HTML elements while let say we have a big component with a lot of children - React will have to create initialize these objects, run lifecycle methods, Javascript will have to allocate memory for them and then modify the actual DOM tree (which is an expensive operation).

However, I would argue this will be only a slight performance issue in the majority of cases.

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166