khevamann / rn-responsive-styles

Responsive styles for react-native and react-native-web
MIT License
40 stars 3 forks source link

Does StyleSheet.create really help with performance? #22

Closed YoushaExT closed 1 year ago

YoushaExT commented 1 year ago

I have just started using this library after reading this article from the author of this library. In the article it is mentioned:

This helper needs to be called globally in the file as React Native StyleSheet performs some optimizations so that it only creates styles once and they are never re-updated. This means there are less trips across the JS-Native bridge, which are very expensive.

but after some research I have come across the claim that Stylesheet.create does not add performance gains (See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/29265#issuecomment-430783289).

khevamann commented 1 year ago

Hi @YoushaExT, yes the performance gains of StyleSheet.create() are a lot of times mis-interpreted. StyleSheet.create() used to provide some pretty good performance improvements, however those have been mostly all removed now. From my understanding StyleSheet.create() currently provides no additional benefits from creating a plain object outside the component. The snippet from the article is saying how you should create the StyleSheet outside the components body vs inside, this is because if you define it in the component then every re-render will re-create the StyleSheet which is much less performant than having it outside where it is only created once.

With that being said you may be wondering why I am still in support of using StyleSheet.create() instead of just an object. I am using it because it is the way react-native has built to do styling, so in the future I am guessing they will come up with performance improvements and re-implement them into the stylesheet. In addition react-native-web has been doing some interesting things with StyleSheet performance that only applied to styles using StyleSheets briefly described here but I have seen it in their release notes more often.

So while I have nothing against using plain objects as styles, I like to use StyleSheets whenever possible to support any future improvements automatically, and there is no downside to using them in my opinion.

Let me know if you have any questions on that.

So:

function Component() {
  return <View style={styles.container} />
}
const styles = StyleSheet.create({ container: { color: 'red' } })

Is just as performant as:

function Component() {
  return <View style={styles.container} />
}
const styles = { container: { color: 'red' } }

but both are more performant than

function Component() {
  const styles = { container: { color: 'red' } }
  return <View style={styles.container} />
}
khevamann commented 1 year ago

@YoushaExT I am going to close this, feel free to reopen if you have any follow up questions or would like more clarification