Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use React native StyleSheet?

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.

like image 938
kkk Avatar asked Mar 10 '17 13:03

kkk


1 Answers

Performance of rendering, better invalid prop values detection and better code quality.

  1. When passing regular style objects into the StyleSheet.create(), the module will freeze the objects and assign each one an ID.

IDs enable optimizations through the bridge and memory in general

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

like image 96
Florin Dobre Avatar answered Sep 30 '22 12:09

Florin Dobre