Skip to content

Commit

Permalink
fix(react-router): memoize Match, MatchInner as well as route compone…
Browse files Browse the repository at this point in the history
…nts to prevent unnecessary re-renders (#2056)
  • Loading branch information
schiller-manuel authored Jul 29, 2024
1 parent 12ad68f commit 06c3a69
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions packages/react-router/src/Match.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ import { renderRouteNotFound } from './renderRouteNotFound'
import { rootRouteId } from './root'
import type { AnyRoute } from './route'

export function Match({ matchId }: { matchId: string }) {
export const Match = React.memo(function MatchImpl({
matchId,
}: {
matchId: string
}) {
const router = useRouter()
const routeId = useRouterState({
select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string,
Expand Down Expand Up @@ -99,8 +103,13 @@ export function Match({ matchId }: { matchId: string }) {
</ResolvedSuspenseBoundary>
</matchContext.Provider>
)
}
function MatchInner({ matchId }: { matchId: string }): any {
})

export const MatchInner = React.memo(function MatchInnerImpl({
matchId,
}: {
matchId: string
}): any {
const router = useRouter()
const routeId = useRouterState({
select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string,
Expand All @@ -127,6 +136,11 @@ function MatchInner({ matchId }: { matchId: string }): any {
},
})

const out = React.useMemo(() => {
const Comp = route.options.component ?? router.options.defaultComponent
return Comp ? <Comp key={matchId} /> : <Outlet />
}, [matchId, route.options.component, router.options.defaultComponent])

// function useChangedDiff(value: any) {
// const ref = React.useRef(value)
// const changed = ref.current !== value
Expand Down Expand Up @@ -236,10 +250,6 @@ function MatchInner({ matchId }: { matchId: string }): any {
throw match.loadPromise
}

const Comp = route.options.component ?? router.options.defaultComponent

const out = Comp ? <Comp /> : <Outlet />

return (
<>
{out}
Expand All @@ -248,9 +258,9 @@ function MatchInner({ matchId }: { matchId: string }): any {
) : null}
</>
)
}
})

export const Outlet = React.memo(function Outlet() {
export const Outlet = React.memo(function OutletImpl() {
const router = useRouter()
const matchId = React.useContext(matchContext)
const routeId = useRouterState({
Expand Down

0 comments on commit 06c3a69

Please sign in to comment.