How to make React Native mobile application faster?

前端 未结 5 645
盖世英雄少女心
盖世英雄少女心 2021-02-02 15:45

React Native mobile application is working very slow on every click. I am using react native v0.40.0 and following are the dependencies of my proje

5条回答
  •  一向
    一向 (楼主)
    2021-02-02 16:14

    Here are some advices for optimization react-native:

    1. Parsing and serializing (such as response.json() or JSON.stringify) blocks js thread, so all JS animations and handlers (such as onScroll and onPress, and of course render method) suffer from this. Try to load from backend only data that you need to show.
    2. Use native animations (useNativeDriver: true parameter) where it is possible, and try not to use onScroll. Also, consider using react-native-reanimated for animations.
    3. Optimize you render method and try to make its calls as rare as possible. It is called when component's props or state changed.
    4. Understand how PureComponent and React.memo work and try to use them where necessary. But keep in mind that they also can slow the app down if not used correctly.
    5. Always use StyleSheet for styles, it cashes them and replaces with style id (integer), so styles are passed to native side only once and then style ids are used.

    Bad:

    // style object is created on every render
    render() {
        return 
    }
    

    Good:

    render() {
        return 
    }
    
    // style is created once
    const styles = StyleSheet.create({
        flex: { flex: 1 }
    });
    
    1. Same with functions.

    Bad:

    // onPress handler is created on every render
    render() {
        return  this.props.navigator.navigate('SignIn')}/>
    }
    

    Good:

    render() {
        return 
    }
    
    // onPressSignIn is created once
    onPressSignIn = () => {
        this.props.navigator.navigate('SignIn');
    }
    
    1. Big O of all operations on client should be constant. Enumerate arrays as less as you can. Always use Object and Set instead of Array where it is possible. Use pagination when you need to load big amounts of data from server / database, leave sorting and other heavy calculations for server.

    For example if you often need to get objects by id, it is better to use:

    let items = {
        "123": { id: "123", ... },
        "224": { id: "224", ... }
    };
    
    let item = items["123"];
    

    instead of usual array:

    let items = [
        0: { id: "123", ... },
        1: { id: "224", ... }
    ];
    
    let item = items.find(x => x.id === "123");
    
    1. Check out this doc: https://reactnative.dev/docs/performance

提交回复
热议问题