Skip to content

Instantly share code, notes, and snippets.

@rikkrome
Last active June 30, 2022 17:31
Show Gist options
  • Save rikkrome/778ec0eeff17f73dd5b68b4836cdcfe8 to your computer and use it in GitHub Desktop.
Save rikkrome/778ec0eeff17f73dd5b68b4836cdcfe8 to your computer and use it in GitHub Desktop.

React Native Performance Tips

  • Lazy loading screens
    • bottom tabs & top tabs
  • Tracking renders
    • counting the amount of times a component renders.
    • added a custom useRef() hook into all components / child components.
import { useRef } from 'react';

const getStyle = (current) => {
  switch (true) {
    case current >= 10:
      return 'background: black ; color: #FFFF00; font-size:13px';
    case current >= 20:
      return 'background: black ; color: red; font-size:13px';
    default:
      return 'background: black ; color: green; font-size:13px';
  }
}

const useCountRenders = (name) => {
  if (__DEV__) {
    const renders = useRef(0);
    const current = renders.current++;
    const style = getStyle(current);
    console.log(`%c${name} renders: %c${current}`, style, style);
  }
};

export default useCountRenders;

YouTube (Ben Awad) React Hooks useCallback Tutorial

React.memo()

If your function component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.

React Hooks

  • useCallback : Returns a memoized callback
  • useMemo : Returns a memoized value

Gotchas

No inline prop functions, arrays, or objects

👎

<Comp
  onPress={()=>{
    // handle press
  }}
  style={{ flex: 1 }}
  data={[ 1, 2, 3] }
/>

👍

functional components

const handlePress = useCallback(()=>{
    // handle press
}, [])

const data = useMemo(() => [ 1, 2, 3], [])

<Comp
  onPress={handlePress}
  style={styles.idk}
  data={data}
/>

class component

  handlePress = () => {
    // handle press
  }
  render() {
    return (
      <View>
        <Comp 
          onPress={handlePress} 
          style={styles.idk}
          data={data}
        />
      </View>
    )
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment