Closed hiyaryan closed 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.
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
andtypeWriter
functions inside theuseEffect
hook. In a production environment, theHome
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 theuseEffect
hook. This variable is initially set to true when the component mounts. Before each state update inside thesetTimeout
andtypeWriter
functions, ( check ifisMounted
is still true, ensuring that we only update the state if the component is still mounted. In the cleanup function of theuseEffect
hook, I setisMounted
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.