eslint-plugin-react-native icon indicating copy to clipboard operation
eslint-plugin-react-native copied to clipboard

no-unused-styles reports false positive when used inside React.useMemo

Open janKir opened this issue 4 years ago • 3 comments

When I memoize a Stylesheet that derives some styles from props or state, the react-native/no-unused-styles reports an error although the memoized object is used.

Unused style detected: undefined.box eslint(react-native/no-unused-styles)

Example:

export const Foo = ({bar}) => {
  const styles = React.useMemo(() => Stylesheet.create({
    box: {
      margin: bar,
    },
  }),[bar]);

  return <View style={styles.box} />;
}

janKir avatar Dec 09 '20 12:12 janKir

Never use StyleSheet.create inside useMemo. Need to create rule for that.

gentlee avatar Aug 19 '22 06:08 gentlee

The assumption is correct. Dynamic styles should be memoized to prevent triggering re-renders. A simple benchmark with Why Did You Render would show that. The most expensive operation for RN is converting back and forth data to JSON to propagate the unnecessary changes over the bridge, therefore YES: memoize your dynamic styles.

vdyalex avatar Aug 24 '22 16:08 vdyalex

I totally stand with this. I often need to move some styles in the component to make a dynamic stylesheet object, but I also need to memoize them for performance purposes.

So this is definitely an issue.

apapalillo avatar Mar 06 '24 19:03 apapalillo