As per title:
What’s the difference of these usages? I can see they all performing the same from UI perspective
import { StyleSheet, View } from 'react-native'
import type { JSX } from 'react'
const App = (): JSX.Element => (
<View>
<View style={[styles.viewA, styles.viewB]} />
<View style={StyleSheet.compose(styles.viewA, styles.viewB)} />
</View>
)
const styles = StyleSheet.create({
viewA: {
width: 100,
height: 100,
color: '#f00'
},
viewB: {
color: '#0f0'
}
})
2
Answers
From your example, using both are same since styles are static.
compose
is useful when styles are dynamic. See the official description belowStylsheet.compose(style1, style2)
combines two styles such thatstyle2
will override any styles instyle1
. If either style is falsy, the other one is returned without allocating an array, saving allocations and maintaining reference equality for PureComponent checksReference : react-native/Libraries/StyleSheet/StyleSheet.js
I think there was a time when
StyleSheet.compose
would have been more performant. I think the object returned byStyleSheet.create
used to go through some type of optimization. In the commit whereStyleSheet.create
is changed to be an identity function, they say it will no longer return a number. So before that change occurred, unless there was some magic going on under the hood, I dont think you could merge styles without using that function.Since the change,
StyleSheet.flatten
andStyleSheet.compose
seem obsolete. Outside of doing style preprocessing,StyleSheet
as a whole seem obsolete.I think the reason it remains in use is out of tradition/convention.