hyrwork / react-native-row

A wrapper around the react-native View component enabling concise assignment of flexbox properties
MIT License
51 stars 5 forks source link

cache Styles #10

Open ssomnoremac opened 7 years ago

ssomnoremac commented 7 years ago

so as it turns out styles should be cached for performance. Stylesheet uses a method called ReactNativePropRegistry.register(obj[key]); which effectively takes a style sheet like

let sheet = Stylesheet.create({
    red: {
        color: 'red'
    },
    blue: {
        color: 'blue'
    }
})

and creates an object with cached references (simple numbers)

sheet = {
    red: 17,
    blue: 18
}

So because this library uses inline styles we should be using number references for styles as well instead of actual styles. Should be fun and pretty easy to implement.

eightyfive commented 6 years ago

Hi,

I quickly threw an implementation on my local machine. I would like to know if I am heading in the right direction before I submit a proper pull request.

So the idea is, I build the style object:

const _style = shorthandStyles(margin, padding);

_style.flex = typeof _flex === "number" ? _flex...

_style.justifyContent = spaceBetween ? "space-between"...

_style.alignItems = stretch ? "stretch"...

_style.flexDirection = reverse ? "column-reverse"...

Then I use the serialized _style object as a cache key:

const key = JSON.stringify(_style);

if (typeof cache[key] === "undefined") {
  Object.assign(cache, StyleSheet.create({ [key]: _style }));
}

return cache[key];

Ending up in:

return (
    <RNView style={[Sheets.get(_style), style]} {...props}>
      {children}
    </RNView>
  );

Let me know.

PS: The "dial" shorthand idea is excellent.

eightyfive commented 6 years ago

Here is my implementation: https://github.com/eightyfive/react-native-row/commit/eff3bff14a5c256be47625dbc967fbe72990a3f9