How to avoid to re-render children when updating style via props or state in React?

Viewed 2549

At the root of my App I have two React components, Menu and Main. The Menu is hidden by translating it to the left outside of the viewport. When it is visible, I also want the Main content to translate to the right. In order to do that I simply pass a menuOpened property (boolean) to both components. It will apply a conditional style that setup the CSS transform property translateX(). The problem is, when I update the prop, all the children will re-render. Is there a better practice for changing style of a component depdending of a state / props?

2 Answers

As a comment mentioned - a "rerender" is not expensive. Since almost nothing in your DOM tree has changed, the diff is tiny, and so the actual changes are small.

But if you really want to control when a component re-renders, you can use the React life-cycle method shouldComponentUpdate(...).

You can add an additional class (for example app_with-menu) to your App container which indicates if the menu is opened or not. And then style in CSS like this:

.app .content {
   // style for content when menu is closed
}
.app.app_with-menu .content {
   // style for content when menu is opened
}
Related