Skip to content

Instantly share code, notes, and snippets.

@ohtangza
Created August 19, 2018 02:27
Show Gist options
  • Save ohtangza/d93117b9fa63736c9fb406b12d5c1336 to your computer and use it in GitHub Desktop.
Save ohtangza/d93117b9fa63736c9fb406b12d5c1336 to your computer and use it in GitHub Desktop.
const styleObject = StyleSheet.create({
merged: {
color: 'black',
fontSize: 11,
},
black: {
color: 'black',
},
smallFont: {
fontSize: 11,
},
});
const plainObject = {
black: {
color: 'black',
},
smallFont: {
fontSize: 11,
},
};
console.log('#1', styleObject.black, styleObject.smallFont); // => 463 464
console.log('#2-1', StyleSheet.flatten(styleObject.black/* number */)); // => Object {color: "black"}
console.log('#2-2', StyleSheet.flatten(plainObject.black/* object */)); // => Object {color: "black"}
console.log('#3-1', StyleSheet.flatten([styleObject.black, styleObject.smallFont])); // => Object {color: "black", fontSize: 11}
console.log('#3-2', StyleSheet.flatten([plainObject.black, plainObject.smallFont])); // => Object {color: "black", fontSize: 11}
console.log('#4', StyleSheet.flatten({ ...plainObject.black, ...plainObject.smallFont })); // => Object {color: "black", fontSize: 11}
/*
Here is my conclusion:
1) Whenever you use `StyleSheet.flatten()`, there will be only a performance loss, no gain.
2) The reason why we should use it is to look up the original style object from style id.
3) I don't find any difference between `StyleSheet.flatten()` and the spread operator when generating plain style object.
4) `StyleSheet.flatten()` both accept style id and style object, which means that it's more error-safe. But, I think we should strictly restrict its use whenever possible.
5) Regarding the question of performance difference between an merged object and non-merged objects given as a array, But, I don't think there is a big performance difference because it's known fact that RN and native code communicate in JSON. I think it's better to prioritize readability against performance if you are hesistant between those two.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment