Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Previous data showing even though cleaning up in useEffect

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Cleanup function should appear before closing-brace of the useEffect hook

useEffect(() => {
  if (isFocused) {
    const loadSessions = async () => {
      if (client?.id) {
        dispatch(await loadClientSessions(client?.id));
      }
    };
    loadSessions(props);
  }

  return () => dispatch(unloadSessions()); // Cleaning up here... // <--- here
}, [isFocused, client?.id]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading