Why should I use this:
const styles = StyleSheet.create({
...
});
instead of this:
const styles = {
...
};
Properties that StyleSheet provides don't seem very needful to me.
StyleSheet.create()
, the module will freeze the objects and assign each one an ID.IDs enable optimizations through the bridge and memory in general
Some type or prop value validity checks of Stylesheet objects could warn you or help you fix some invalid style issue better than when using the normal object approach.
By moving styles away from the render function, you're making the code easier to understand. Naming the styles is a good way to add meaning to the low level components in the render function.
From what I've seen, both work (normal object, StyleSheet object) when setting the style of a component, even when you pass an array of objects.
Disadvantages when using the StyleSheet
object:
1) you cannot make a comparison like this styles.myNiceComponent.backgroundColor === 'blue'
More details about this disadvantage here: Why can't we check a style attribute of a react-native app?
2) Recomputing styles based on some criteria (like screen rotation) needs some additional infrastructure code to determine which styles to use. If you use simple objects they could be recomputed on the fly every time.
Sources: https://reactnative.dev/docs/stylesheet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With