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:
- Define values outside of the function component body unless the value depends on props (or internal state).
- 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).
Make sure the styles you create a are referentially stable too also when defining components.
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
2. Memoize value within the render method
useMemo()to memoize arrays and objects;useCallback()to memoize callbacks.