skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. I think there was a time when StyleSheet.compose would have been more performant. I think the object returned by StyleSheet.create used to go through some type of optimization. In the commit where StyleSheet.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 and StyleSheet.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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search