react-nativereact-native-stylesheet

What's the difference of using `array` vs `StyleSheet.compose()` in React Native


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'
  }
})

Solution

  • From your example, using both are same since styles are static. compose is useful when styles are dynamic. See the official description below

    Stylsheet.compose(style1, style2) combines two styles such that style2 will override any styles in style1. If either style is falsy, the other one is returned without allocating an array, saving allocations and maintaining reference equality for PureComponent checks

      compose<T: DangerouslyImpreciseStyleProp>(
        style1: ?T,
        style2: ?T,
      ): ?T | $ReadOnlyArray<T> {
        if (style1 != null && style2 != null) {
          return ([style1, style2]: $ReadOnlyArray<T>);
        } else {
          return style1 != null ? style1 : style2;
        }
      },
    

    Reference : react-native/Libraries/StyleSheet/StyleSheet.js