Is there any way to save and restore the navigation history in react-navigation (react-native)

I have a StackNavigator(1) with 5 screens. After 3rd screen I am navigating into another StackNavigator(2) screen and after some action on the second StackNavigator(2) screen I need to come back to Stack StackNavigator(1) 4th screen and should be able to go back to history in StackNavigator(1) using navigation.goBack()

I am able to come back to Stack StackNavigator(1) 4th screen but when i use navigation.goBack() it is not going to StackNavigator(1) 3rd screen

I need to save and restore the navigation history in StackNavigator(1).

Please let me know is there any way to achieve this.

Use StackNavigator.router.getStateForAction to manipulate your route state.

    //assume your StackNavigator1 just like below
    const StackNavigator1 = new StackNavigator({
        Screen1: {screen: Screen1},
        Screen2: {screen: Screen2},
        Screen3: {screen: Screen3},
        Screen4: {screen: Screen4},
        Screen5: {screen: Screen5}
    });

    const defaultGetStateForAction = StackNavigator1.router.getStateForAction;
    //store the state when navigate to screen3
    let state3;

    StackNavigator1.router.getStateForAction = (action, state) => {

        let newState = defaultGetStateForAction(action, state);
        //print out the state object
        console.log(`newState: ${newState}`);

        //change all the routeName 'Screen3', 'Screen4' to match your own project
        if (action.type === 'Navigation/NAVIGATE' && action.routeName === 'Screen3') {
            //store the state of screen3 for restore it later
            state3 = newState;
        }

        if (action.type === 'Navigation/NAVIGATE' && action.routeName === 'Screen4') {
            //check if screen3 exist in the state, change the condition for your own need
            let result = newState.routes.find((route) => {
                return route.routeName === 'Screen3'
            });
            //if 'screen3' doesn't exist, add it to the route manually
            if (result === undefined && state3 !== undefined) {
                let route4 = newState.routes[newState.index];
                let routes = state3.routes.slice();
                routes.push(route4);
                return {index: 3, routes}
            }
        }

        return defaultGetStateForAction(action, state)
    };

//... the rest code