Skip to content Skip to sidebar Skip to footer

Compare The Performance Between Hiding React Components With Css And State Management

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 (
{ thi

Solution 1:

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.


Solution 2:

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.


Post a Comment for "Compare The Performance Between Hiding React Components With Css And State Management"