How to save a rendered component to memory?

Viewed 2548

I'm developing a React Native application (although I think my issue applies to React in general) made of multiple screens.

So I've created a simple component to switch the screens:

import React, { Component } from 'react';
import { connect } from 'react-redux'
import { View } from 'react-native';

class AppNavComponent extends Component {

    constructor() {
        super();
        this.screenCache_ = {};
    }

    render() {
        if (!this.props.route) throw new Error('Route must not be null');
        let route = this.props.route;
        if (this.screenCache_[route.routeName]) return this.screenCache_[route.routeName];
        let Screen = this.props.screens[route.routeName].screen;

        this.screenCache_[route.routeName] = (
            <View>
                <Screen/>
            </View>
        );

        return this.screenCache_[route.routeName];
    }

}

const AppNav = connect(
    (state) => {
        return {
            route: state.route,
        };
    }
)(AppNavComponent)

export { AppNav };

this.props.screens contains the list of screens, and this.props.route the route that needs to be displayed. The component works fine, but my problem is that I'd like to cache to memory certain screens because they are slow to render (a large list) and they lose the scrolling position whenever React re-render them.

In the example above, I've tried to save the rendering to this.screenCache_ but that's probably not the right approach as the screens are still re-rendering when I load them, go to another page, and go back to them.

I guess that's a common problem but I can't find any information on Google. Any suggestion on how to do this?

3 Answers
Related