We are building a Live Auction App. When a user places a bid, we need to show a 'Success' message that automatically disappears after 5 seconds. However, we've noticed two major bugs in our prototype:
If the user navigates away from the page before the 5 seconds are up, the app crashes because it tries to update the state of an unmounted component.
If the user places a second bid while the first timer is still running, the timers overlap, causing the message to flicker and disappear too early.
The Task: Implement a production-ready useTimeout(callback, delay) hook that:
Encapsulates Lifecycle: Automatically handles
setTimeoutandclearTimeout.Prevents Memory Leaks: Ensures no code runs after the component unmounts.
Supports Dynamic Pausing: If the
delaypassed isnull, the timer should stop (useful for 'pausing' an action if the user hovers over the message).Solves Stale Closures: If the
callbackchanges (e.g., it relies on new state), the timeout must always execute the latest version of that logic without you having to manually reset the timer every single time a dependency changes.