skip to Main Content

I am using a Modal in my RN app to show a map to the user. This component is slow and expensive to load, which is why I want to make sure it is not getting loaded from scratch every time.

However, currently this is not working. By toggling visible, the map component gets loaded from scratch each and every time the modal opens up again.

Is there a way to prevent this behavior and make sure that the map is not getting unmounted and reloaded every time?

import { Modal } from 'react-native';

<Modal
  animationType="slide"
  transparent={true}
  visible={showModal}
  onRequestClose={() => setShowModal(false)}>
  <MapView onTogglePressed={() => setShowModal(false)} />
</Modal>

Note: I do not have to use the Modal. Alternative components would be acceptable too.

2

Answers


  1. Using this code, you can avoid unmounting and reloading the MapView component every time the modal opens up again.

    import React, { useState } from 'react';
    import { View, TouchableOpacity, Text } from 'react-native';
    import MapView from './MapView'; // Import your MapView component
    
    const App = () => {
      const [showMap, setShowMap] = useState(false);
    
      return (
        <View>
          <TouchableOpacity onPress={() => setShowMap(true)}>
            <Text>Show Map</Text>
          </TouchableOpacity>
    
          {showMap && (
            <View style={{ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }}>
              <TouchableOpacity onPress={() => setShowMap(false)}>
                <Text>Close Map</Text>
              </TouchableOpacity>
              <MapView />
            </View>
          )}
        </View>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
  2. I do have a couple of suggestions that you can work with:

    1. Use React memo:
    const MemoizedMapView = React.memo(MapView);

    Wrapping with memo can prevent re-rendering for functional components.

    Then use it in your Modal like:

    <Modal
      animationType="slide"
      transparent={true}
      visible={showModal}
      onRequestClose={() => setShowModal(false)}
    >
      <MemoizedMapView onTogglePressed={() => setShowModal(false)} />
    </Modal>
    1. Use key prop:
    <Modal
      animationType="slide"
      transparent={true}
      visible={showModal}
      onRequestClose={() => setShowModal(false)}
    >
      <MapView key={someUniqueKeyHere} onTogglePressed={() => setShowModal(false)} />
    </Modal>

    I hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search