Why Our Users Kept Getting Logged Out: Three Timer Bugs in One React Hook
Reading time: 3 minutesThe bug report was simple: “I keep getting logged out.” Not on every visit, not at a fixed time, just often enough that people working in the dashboard for a while would suddenly find themselves back on the sign-in screen, sometimes in the middle of a task.
The session logic was small: an access token that expires, and a React hook that refreshes it in the background before it does. When I finally sat down with that hook, I found not one bug but three, each hiding the others.
The hook
Simplified, the original looked like this:
const ACCESS_TOKEN_TTL = 10 * 60 * 1000; // tokens expire after 10 minutes
const REFRESH_AFTER = 13 * 60 * 1000; // ...and we refresh after 13
function useTokenRefresh({ onExpired }: { onExpired: () => void }) {
const refresh = async () => {
const ok = await auth.refresh();
if (!ok) onExpired();
};
useEffect(() => {
const id = setTimeout(refresh, REFRESH_AFTER);
return () => clearTimeout(id);
}, [refresh]);
}
It looks reasonable at a glance. It has three problems.
Bug 1: refreshing after the token is already dead
Look at the two constants together: the token lives for 10 minutes, and the refresh is scheduled after 13. For three minutes of every cycle, the user is holding an expired token. Any request in that window fails, and the app reacts to the failure by signing them out.
Nobody wrote “refresh after expiry” on purpose. The two values lived in different places, were changed at different times, and nothing tied them together.
The fix is to derive one from the other, with a margin:
const REFRESH_MARGIN = 60 * 1000; // refresh one minute before expiry
const refreshIn = (expiresAt: number) => Math.max(0, expiresAt - Date.now() - REFRESH_MARGIN);
Better still is to schedule from the token’s actual expiry (expiresAt, from the token or the auth response) rather than from a constant, so a change on the server side cannot silently break the client again.
Bug 2: a timer that fires once
setTimeout runs once. So even with the right delay, the hook would refresh the token a single time and then never again. A user who stayed in the app for longer than two token lifetimes would always be logged out eventually.
The fix in my commit was to make the refresh repeat, with setInterval:
useEffect(() => {
const id = setInterval(refresh, ACCESS_TOKEN_TTL - REFRESH_MARGIN);
return () => clearInterval(id);
}, []);
There is a second valid design: keep setTimeout, but reschedule after each refresh using the new token’s expiry. That handles tokens whose lifetime changes and avoids drift, at the cost of slightly more code. For a fixed lifetime, the interval is simpler and easier to read; the important part is that the refresh keeps happening.
Bug 3: an effect that keeps resetting the timer
The original effect depended on refresh. But refresh was a new function on every render, so every re-render tore down the timer and started a new one from zero.
In a busy dashboard, components re-render constantly. A timer that restarts on every render may never reach its delay at all. This bug actually masked the other two in quiet sessions and made them worse in busy ones, which is why the reports felt random.
The fix is to keep the effect’s dependencies stable and read the latest callback through a ref:
function useTokenRefresh({ onExpired }: { onExpired: () => void }) {
const onExpiredRef = useRef(onExpired);
useEffect(() => {
onExpiredRef.current = onExpired; // always the latest callback
});
useEffect(() => {
const refresh = async () => {
const ok = await auth.refresh();
if (!ok) onExpiredRef.current();
};
const id = setInterval(refresh, ACCESS_TOKEN_TTL - REFRESH_MARGIN);
return () => clearInterval(id);
}, []); // set up once, never reset by renders
}
The timer is created once, when the component mounts, and only cleared when it unmounts.
One more thing timers don’t tell you
Browsers throttle timers in background tabs, and a laptop that goes to sleep pauses them entirely. A user who closes their laptop for an hour comes back to an expired token no matter how correct the interval is.
So the hook also checks when the tab becomes visible again, and refreshes right away if the token is close to expiry:
useEffect(() => {
const onVisible = () => {
if (document.visibilityState === "visible" && auth.expiresSoon(REFRESH_MARGIN)) {
void auth.refresh();
}
};
document.addEventListener("visibilitychange", onVisible);
return () => document.removeEventListener("visibilitychange", onVisible);
}, []);
Why three bugs looked like one
Each bug on its own would have been easy to spot. Together, they produced a symptom with no clear pattern:
- Bug 1 made every cycle fail for three minutes.
- Bug 2 made long sessions fail eventually.
- Bug 3 made the timing depend on how busy the page was.
That is why “I keep getting logged out” never reproduced on demand. The lesson I took away is to test time-based code with fake timers, advancing the clock past expiry and through several refresh cycles, instead of waiting and hoping:
vi.useFakeTimers();
renderHook(() => useTokenRefresh({ onExpired }));
vi.advanceTimersByTime(3 * ACCESS_TOKEN_TTL);
expect(auth.refresh).toHaveBeenCalledTimes(3);
expect(onExpired).not.toHaveBeenCalled();
Takeaways
- Derive related timing values from one source. A refresh delay that is not computed from the expiry will eventually drift past it.
- One-shot vs repeating is a real decision. Choose
setInterval, or asetTimeoutthat reschedules itself, on purpose. - Effect dependencies are part of the behaviour. An unstable dependency turns a timer into “restart on every render”. Stabilise callbacks with refs.
- Timers are not clocks. Handle background tabs and sleep with a visibility check.
- Fake timers make time-based bugs reproducible. If it depends on time, test it by controlling time.