What is the difference between StyleSheet.compose and StyleSheet.flatten?

Viewed 1151

I'm trying to see what's the difference between StyleSheet.compose and StyleSheet.flatten methods. From their documentation it sounds the same except that flatten appears to modify the original data and whereas compose has no side effects. Am I interpreting it correctly?

1 Answers

I read the codes of React Native and these difference is trivial now.

If you use compose, in case the args of two styles are both exist, simply concatenate them to style array. In the other case of either or both are falsy value, simply return existing style or undefined value. This is useful for if having base styles with dynamic style by some special conditions because shallow comparison does not evaluate dynamic one unless conditions matched.

The flatten is now the function only merge multiple styles with overriding former elements. Once it stores reference of style objects, but now it override styles rather than flatten styles.

So, I recommend to use compose function for convenience and it resolve standard style props interface.

See below links in detail.

https://github.com/facebook/react-native/blob/dc80b2dcb52fadec6a573a9dd1824393f8c29fdc/Libraries/StyleSheet/StyleSheet.js

https://github.com/facebook/react-native/blob/dc80b2dcb52fadec6a573a9dd1824393f8c29fdc/Libraries/StyleSheet/flattenStyle.js

Related