Skip to main content

Avoiding re-renders in React

@unwind/class-name allows your components to accept more complex value types than a simple string. React does a shallow compare when deciding whether to update components wrapped with memo().

To avoid unnecessary re-renders due to className prop accepts types of values other than simple string type, make sure the value is referentially stable.

Here are some of the options to mitigate re-rendering components:

  1. Define values outside of the function component body unless the value depends on props (or internal state).
  2. Memoize value inside the function body when it depends on the props (or internal state).

Example

In this example we define functional component Box. We can define boxClassName (the component's class name value) outside of the functional component (render block).

caution

Make sure the styles you create a are referentially stable too also when defining components.

Live Editor
Result
Loading...
tip

We can also omit the second parameter of the ClassNameCallback since it uses an HTMLDivElement element because its className prop accepts only a string | undefined.

Omitting the previously generated class selectors would effectively remove every generated selector if we'd wrapped another unwind component instead of the HTMLDivElement.


1. Outside of the function component body

Live Editor
Result
Loading...

2. Memoize value within the render method

Live Editor
Result
Loading...