I'm comming from a ReactJS background. There, I use useEffect
to keep the state updated in my components. Whenever I mount them, I make an API request and show the updated state.
I'm now developing for React Native and using React Navigation. In React Navigation, screens aren't unmounted when the user navigate to another screen, so useEffect
won't always fetch the API when a user comes back to a screen that was previous rendered.
Reading the React Navigation documentation, I see they have a useFocusEffect
hook, which is called everytime a screen comes back in focus.
Their hook, however, seems to have a big boilerplate to replicate in each screen I need to always fetch updated data:
useFocusEffect(
React.useCallback(() => {
let isActive = true;
const fetchUser = async () => {
try {
const user = await API.fetch({ userId });
if (isActive) {
setUser(user);
}
} catch (e) {
// Handle error
}
};
fetchUser();
return () => {
isActive = false;
};
}, [userId])
);
I tried to create my custom hook based using their useFocusEffect
hook, but since the hook is not in the screen, I came into a problem of the hook not being called.
So my question is, what's the best way to keep my React Native state in sync with my backend and avoid unnecessary requests?
I'm used to Redux, so any solution that uses Redux is also appreciated. I just don't want to add to much complexity to Redux.
Thanks