"Cannot update a component (Router) while rendering a different component" — what actually causes it

If you’ve seen this one in a Next.js App Router app, you know it is not a helpful error:
Cannot update a component (`Router`) while rendering a different component (`LoggerPlayground`).It names a component you never wrote (Router), blames one you did (LoggerPlayground), and points at no line of code. I hit it while building nextjs-logger. The fix was one setTimeout(fn, 0) in exactly the right place. Understanding why took much longer than typing it.
This post is the explanation I wish I’d had. No React internals knowledge needed — I’ll build it up from scratch.
The rule React is enforcing
React has one rule here, and it is simple:
While React is rendering component A, nothing is allowed to change the state of component B.
Rendering, to React, means “calling your component function to find out what it wants to show.” It is supposed to be a question, not an action. If answering the question also changes some other component’s state, React has to start over — it already decided what B looks like, and now B is different. So it refuses, and prints that error.
The confusing part is the word Router. You never call setState on a router. But Next’s App Router is a React component holding state, and some things you do reach in and change it without looking like they do.
The promise that caused the problem
One thing this logger promises is that you can call log.info('...') anywhere — including straight inside a component body, with no useEffect, no readiness check:
function LoggerPlayground() {
log.info('rendered') // allowed, by design
return <div>...</div>
}That is a genuinely nice property. Most logging setups make you wrap a log in an effect just to record a value you already have in your hand.
But it means every log call is a candidate for running during the render phase, which is a far stricter place to be than it looks. Two paths in the package ran there:
- A component logging directly in its body, as above.
LoggerBootstrapClient’s own render body drainingpreInitBuffer— logs that piled up before the client logger finished starting.
Both ran during render, by design. And both could end up calling a Next.js Server Action.
A Server Action is not just an async function
This is the piece I had wrong. Imported into client code, a Server Action looks completely ordinary:
'use server'
export async function relayLogEntries(entries: LogEntry[]) {
// ...
}await relayLogEntries(entries) // looks like a plain callIt is not a plain call. Importing a 'use server' function into client code does not hand you the function — it hands you a reference to one living on the server. Calling that reference goes through React’s Flight client, into Next’s callServer, and into the App Router’s action queue.
That queue is a state update on the Router. Every call. Whether or not anything you’d call “navigation” is happening.
So: log from render → Server Action → Router state update → the error at the top of this post.
There’s a sibling error from the same cause at a different moment. Fire the same call from a timer that runs before the router has committed its first render and you get Can't perform a React state update on a component that hasn't mounted yet. I hit both, from two different code paths, before I realised they were one bug wearing two masks.
The actual trigger: a throttle’s leading edge
Here is the detail that took me longest, and the one I’d have wanted spelled out.
Log calls don’t go straight to the network. They go through a pacing layer — one policy per log level: throttle, debounce, or rate limit. My first assumption was that pacing made the whole question moot. Surely a throttled call is a delayed call, so nothing can happen during render?
No. A throttle with a leading edge fires the first call immediately, then blocks the rest of the window. Leading-edge-first is the normal, sensible default for a throttle — you want the first event to feel instant. But it means the very first log.info() in a render body ran its flush synchronously, on the render stack, straight into the relay, straight into the Server Action, straight into the Router.
That’s why the bug looked random. The first log of a window exploded; the next twenty, inside the throttle window, were silently fine. Same code, same component, different outcome depending on when you happened to hit it.
Why the fix is a macrotask, not a microtask
So: defer the flush off the render stack. My first attempt used a microtask, because it felt lighter and less flaky than a timer:
Promise.resolve().then(() => flush()) // does not workIt did not work, and the reason is specific to how React schedules rendering.
React’s concurrent renderer does not always render your whole tree in one unbroken synchronous run. On a large tree it can pause between slices to let the browser breathe. And when it pauses, queued microtasks get a chance to run — including one you queued from deep inside a component that is part of that same, still-unfinished render.
So a microtask-deferred call can land back inside the very render it was trying to escape. On a small tree it never happens, because React has no reason to pause. On a real app’s tree it happens sometimes. That is the worst kind of bug: clean locally, intermittent in production.
A macrotask does not have that problem. setTimeout(fn, 0) cannot run until the current synchronous work — the whole render pass, every pause point, and every queued microtask — has genuinely finished.
That difference is written into the source as a comment, because it is exactly the thing a future reader would “simplify” back into a promise:
const scheduleOffRenderStack: (fn: () => void) => void =
typeof setTimeout === 'function'
? (fn) => void setTimeout(fn, 0)
: (fn) => void Promise.resolve().then(fn)The promise branch is only a fallback for exotic runtimes with no timer at all.
One choke point, below both transports
The deferral had to go in the right place, and “right” here means below everything.
The Server Action is not the main way logs reach the server. The primary transport is a plain fetch() to a route handler, which never touches the Router and has none of this problem. The Server Action is the fallback, tried only when the route handler answers 404 or every fetch attempt fails — some deployments genuinely can’t reach the route handler, so the fallback earns its place.
My first instinct was to defer only the Server Action call, since fetch was “obviously fine.” That reasoning is correct in isolation and wrong in practice: it leaves two callers able to reach two different behaviours depending on which transport happens to win that render. The choke point isn’t a choke point if traffic can route around it.
So the deferral moved down into enqueue() — the single function every log call passes through, above both transports:
enqueue(entry: LogEntry): void {
// ... push the entry into the ring buffer ...
const level = entry.level
if (!this.pacers.has(level) || this.pendingTriggers.has(level)) return
const timer = setTimeout(() => {
this.pendingTriggers.delete(level)
if (this.isDestroyed) return
this.pacers.get(level)?.()
}, 0)
this.pendingTriggers.set(level, timer)
}A log call now does exactly one thing: append to a buffer. It never calls the pacing layer inline, so it can never reach a transport inline, so it can never reach the Router inline.
The pendingTriggers guard, and why a bare setTimeout isn’t enough
Look at that early return again — this.pendingTriggers.has(level). One scheduled trigger per level, per tick.
Without it, a component logging in a loop — twenty iterations, twenty log.debug() calls — would schedule twenty separate timers. For a throttle that’s merely wasteful, because the flush coalesces anyway. For a rate limit policy it is a real bug: a rate limit counts calls, not pieces of data. Twenty triggers in one tick would burn that level’s entire budget before anything else in the app got a turn.
With the guard, twenty log calls produce twenty buffered entries and one trigger. The data all ships; only the triggering collapses. (A re-rendering component flooding the logging endpoint is the same family of problem seen from the configuration side.)
How I checked it, instead of trusting it
A timing bug can look fixed because your machine got lucky. Three tests pin it, in src/queue/__tests__/client-queue.test.ts:
it("does not call relayEntries synchronously from enqueue(), even on a leading-edge throttle", () => {
const queue = new ClientQueue({
maxQueueSize: 10,
// `leading: true` throttle — the exact policy that fired inline before.
pacerPolicies: { debug: { strategy: "throttle", windowMs: 500 } },
transportOptions: { relayUrl: "/api/log-relay", signedToken: "t", issuedAt: new Date().toISOString() },
})
queue.enqueue(makeEntry(0))
expect(relayEntries).not.toHaveBeenCalled()
queue.destroy()
})That first one is the regression itself: the leading-edge throttle, the one policy that used to fire inline, and an assertion that the transport was not touched before enqueue() returned. It fails against the old code and passes against the new.
The second proves the deferral is a delay and not a drop — enqueue, wait 20ms, expect exactly one relay call. A fix that quietly swallowed logs would pass test one and fail here.
The third pins the coalescing: twenty entries pushed in a loop, then one relay call carrying all twenty.
for (let i = 0; i < 20; i++) queue.enqueue(makeEntry(i))
await new Promise((r) => setTimeout(r, 20))
expect(relayEntries).toHaveBeenCalledTimes(1)
const shipped = (relayEntries as any).mock.calls[0][0] as LogEntry[]
expect(shipped).toHaveLength(20)One call, twenty entries. Nothing lost, nothing fired early.
✓ src/queue/__tests__/client-queue.test.ts (7 tests) 47msWorth being honest about the limit of these: they test the queue, not React. They prove enqueue() never touches a transport on its caller’s stack — which is the actual invariant, and the only one that matters, since React’s render stack is just one caller among others. A test that genuinely drove React’s concurrent renderer into a mid-render pause would be testing React’s scheduler more than my code.
The general shape of this
The error message is Next-flavoured, but the lesson isn’t:
If a library promises “call this from anywhere,” every side effect it performs on your behalf must leave the caller’s stack unconditionally — not only on the paths that look risky.
The paths that look risky are not the problem. The problem is a pacing layer whose leading edge is synchronous, three calls below the one you were reading, under a transport you assumed was the safe one.
If you’re building something with that promise — a logger, an analytics client, anything that syncs to a server as a side effect of rendering — the question is not “is this particular call safe to make synchronously.” It is: is there exactly one place, below every caller and every transport, where I can force a macrotask boundary?
If there isn’t one yet, that’s the refactor to do before someone files a bug about Router.
If you want the wider picture of how these logs get to the server at all, how client logs reach your terminal without a public endpoint covers the transport side of the same package.