cognovi-ai / the-cdj

The Cognitive Distortion Journal (CDJ) is a smart journaling tool that helps remedy distorted thinking. It can feel impossible to follow the CBT technique of labeling and reframing distorted thinking when you've been thinking this way your whole life. The CDJ can help with that 🧠✨ -- v2 is in development!
https://thecdj.app
3 stars 0 forks source link

Prevent state update on unmounted component in useEffect hook. #67

Closed hiyaryan closed 10 months ago

hiyaryan commented 10 months ago

This pull request addresses a bug in the Home component where state updates were being attempted after the component had unmounted, leading to potential memory leaks and unexpected behavior.

The root cause of the issue was the asynchronous nature of the setTimeout and typeWriter functions inside the useEffect hook. In a production environment, the Home component could unmount before these asynchronous operations completed, leading to attempts to update the state of an unmounted component.

To fix this issue, I introduced a variable isMounted inside the useEffect hook. This variable is initially set to true when the component mounts. Before each state update inside the setTimeout and typeWriter functions, ( check if isMounted is still true, ensuring that we only update the state if the component is still mounted. In the cleanup function of the useEffect hook, I set isMounted to false, indicating that the component has unmounted.

This change ensures that we do not attempt to update the state after the Home component has unmounted, preventing potential memory leaks and unexpected behavior. It also aligns with React best practices for handling side effects in function components.

hiyaryan commented 10 months ago

While this fix addresses the immediate issue of state updates on an unmounted component, it's worth noting that this is a temporary solution intended to make the application work correctly in production. The multiple nested if statements within the useEffect hook indicate that there might be a better design solution.

One potential improvement could be refactoring the useEffect hook into a separate component to better isolate its behavior and make the code more maintainable. Alternatively, more thorough debugging could be conducted identify the exact points where memory leaks and unexpected behavior occur, which could lead to a more targeted and efficient solution.