react-native-style-utilities
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

react-native-style-utilities

Fully typed hooks and utility functions for the React Native StyleSheet API


npm i react-native-style-utilities

useStyle

A hook to memoize dynamic styles.

Objects

By using useStyle the object { height: number } gets memoized and will only be re-created if someDynamicValue changes, resulting in better optimized re-renders.

Bad

return <View style={{ height: someDynamicValue }} />

Good

const style = useStyle(() => ({ height: someDynamicValue }), [someDynamicValue])

return <View style={style} />

Arrays

useStyle can also be used to join arrays together, also improving re-render times.

Bad

return <View style={[styles.container, props.style, { height: someDynamicValue }]} />

Good

const style = useStyle(
  () => [styles.container, props.style, { height: someDynamicValue }],
  [props.style, someDynamicValue]
);

return <View style={style} />

useFlatStyle

Same as useStyle, but flattens ("merges") the returned values into a simple object with StyleSheet.flatten(...).

const style1 = useStyle(
  () => [styles.container, props.style, { height: someDynamicValue }],
  [props.style, someDynamicValue]
);
style1.borderRadius // <-- does not work, `style1` is an array!

const style2 = useFlatStyle(
  () => [styles.container, props.style, { height: someDynamicValue }],
  [props.style, someDynamicValue]
);
style2.borderRadius // <-- works, will return 'number | undefined'

findStyle

A helper function to find a given style property in any style object without using expensive flattening (no StyleSheet.flatten(...)).

function Component({ style, ...props }) {
  const borderRadius = style.borderRadius // <-- does not work, style type is complex
  const borderRadius = findStyle(style, "borderRadius") // <-- works, is 'number | undefined'
}

Dependencies (0)

    Dev Dependencies (19)

    Package Sidebar

    Install

    npm i react-native-style-utilities

    Weekly Downloads

    663

    Version

    1.0.1

    License

    MIT

    Unpacked Size

    77.5 kB

    Total Files

    16

    Last publish

    Collaborators

    • mrousavy