I have two screens that are conditionally rendered. I would like the state of the screens to remain the same after navigating away from the screen and returning.
For example, in the reproducible code below, when I am on ScreenA
and scroll the map, click to ScreenB
, and then return to ScreenA
, I would like the map to still be where I originally scrolled. However it renders like new again, erasing the users progress from before.
How can I keep ScreenA at the same place the user was, after navigating to and from ScreenB?
I tried using useCallback as you can see but no luck. The link below takes you to snack.expo.io which contains all the code and a simulator ready to go.
Reproducible code on snack expo io.
Code here as well
export default function App() {
const [screen, setScreen] = useState('A');
function navToA() {
setScreen('A');
}
function navToB() {
setScreen('B');
}
const RenderScreen = useCallback((props) => {
return <ScreenA />;
}, []);
return (
<SafeAreaView style={styles.container}>
{screen === 'A' && <RenderScreen />} // users progress is lost when moving to screenB and back
{screen === 'B' && <ScreenB />}
<TouchableOpacity onPress={() => navToA()} style={styles.buttonStyleA}>
<Text>A</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navToB()} style={styles.buttonStyleB}>
<Text>B</Text>
</TouchableOpacity>
</SafeAreaView>
);
}