Skip to content

Commit 89140b7

Browse files
rschristiansbesh91
andauthored
fix: Memoize route component to avoid double render for incoming async routes (#72)
* fix: Try to fix unnecessary double-render * test: Add test case Co-authored-by: Steven Beshensky <[email protected]> --------- Co-authored-by: Steven Beshensky <[email protected]>
1 parent 24d96b5 commit 89140b7

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

src/router.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,14 @@ export function Router(props) {
145145

146146
/** @type {VNode<any> | undefined} */
147147
let incoming = pathRoute || defaultRoute;
148+
149+
const isHydratingSuspense = cur.current && cur.current.__u & MODE_HYDRATE && cur.current.__u & MODE_SUSPENDED;
150+
const isHydratingBool = cur.current && cur.current.__h;
148151
const routeChanged = useMemo(() => {
149152
prev.current = cur.current;
150153

154+
cur.current = /** @type {VNode<any>} */ (h(RouteContext.Provider, { value: matchProps }, incoming));
155+
151156
// Only mark as an update if the route component changed.
152157
const outgoing = prev.current && prev.current.props.children;
153158
if (!outgoing || !incoming || incoming.type !== outgoing.type || incoming.props.component !== outgoing.props.component) {
@@ -157,12 +162,8 @@ export function Router(props) {
157162
return true;
158163
}
159164
return false;
160-
}, [url]);
165+
}, [url, JSON.stringify(matchProps)]);
161166

162-
const isHydratingSuspense = cur.current && cur.current.__u & MODE_HYDRATE && cur.current.__u & MODE_SUSPENDED;
163-
const isHydratingBool = cur.current && cur.current.__h;
164-
// @ts-ignore
165-
cur.current = /** @type {VNode<any>} */ (h(RouteContext.Provider, { value: matchProps }, incoming));
166167
if (isHydratingSuspense) {
167168
cur.current.__u |= MODE_HYDRATE;
168169
cur.current.__u |= MODE_SUSPENDED;

test/router.test.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,7 @@ describe('Router', () => {
251251
await sleep(10);
252252

253253
expect(scratch).to.have.property('innerHTML', '<h1>B</h1><p>hello</p>');
254+
expect(B).to.have.been.calledOnce;
254255
expect(B).to.have.been.calledWith({ path: '/b', query: {}, params: {}, rest: '' });
255256

256257
B.resetHistory();
@@ -277,6 +278,7 @@ describe('Router', () => {
277278
await sleep(10);
278279

279280
expect(scratch).to.have.property('innerHTML', '<h1>C</h1>');
281+
expect(C).to.have.been.calledOnce;
280282
expect(C).to.have.been.calledWith({ path: '/c', query: {}, params: {}, rest: '' });
281283

282284
// "instant" routing to already-loaded routes

0 commit comments

Comments
 (0)