I have a component in my react native app that loads sessions related to a particular individual. In the useEffect()
of that component I both load the sessions when the component comes into focus, and unload those sessions within the cleanup.
export const ClientScreen = (props) => {
const isFocused = useIsFocused();
const client = useSelector((state) => selectActiveClient(state));
useEffect(() => {
if (isFocused) {
const loadSessions = async () => {
if (client?.id) {
dispatch(await loadClientSessions(client?.id));
}
return () => dispatch(unloadSessions()); // Cleaning up here...
};
loadSessions(props);
}
}, [isFocused, client?.id]);
const updatedProps = {
...props,
client,
};
return <ClientBottomTabNavigator {...updatedProps} />;
};
Generally the component is working as expected. However, I do notice that if I load the component with one client, then navigate away, and then come back to the component by loading a new client, that for a brief moment the sessions pertaining to the previous client show before being replaced the sessions relevant to the new client.
My question is, shouldn’t the unloadVisits()
that runs on cleanup — which sets sessions to an empty array — prevent this? Or is this some kind of react behavior that’s holding onto the previous state of the component? How can I ensure this behavior doesn’t occur?
2
Answers
Cleanup function
should appear before the closing-brace of theuseEffect
hookas commented,
your, but you don’t do anything with it. And the effect where you callloadSessions
returns a cleanup functionloadSessions(props)
does not return anything, that’s why it does not clean up.Edit:
I made a mistake,
loadSessions
returns a Promise of a cleanup function. And it is impossible to "unwrap" this Promise and get to the cleanup function itself in a way that you can return it in your effect. You have to move the cleaup function out of theasync function loadSessions
.But you don’t need
async/await
for everything: