React Navigation renders all tabs at once

Viewed 1560

I have a bunch of react navigation tabs and one of them opens up the camera. The problem is when the application loads, react navigation instantly renders all the pages at once so the camera is on even if I can't see it. The router file is just a bunch of StackNavigator objects representing each page, loaded into the TabNavigator object.

How can I only render the page I'm going to so that the camera isn't on when it doesn't need to be?

3 Answers

set lazy:false in BottomTabNavigatorConfig

I had almost the same issue - the camera was used in one the main tabs of my app.
You can use 'useFocusEffect' from '@react-navigation/native':
https://reactnavigation.org/docs/use-focus-effect/

Here is an example:

import React, { useState} from 'react';
import { useFocusEffect } from '@react-navigation/native';

export default function cameraOnFocusOnly() {
    const [cameraActive, setCameraActive] = useState(false);
    useFocusEffect(
        React.useCallback(() => {
            // Do something when the screen is focused
            setCameraActive(true);

            return () => {
                // Do something when the screen is unfocused
                setCameraActive(false);
            };
        }, [])
    );

    return (
        <View>
            {cameraActive && <CameraComponent/>}
        </View>
    );
}
Related