Skip to content

Commit

Permalink
fix: memoize onExitComplete handler (#2802)
Browse files Browse the repository at this point in the history
  • Loading branch information
custardcream98 authored Oct 8, 2024
1 parent 53885c4 commit 6b27a80
Showing 1 changed file with 18 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client"

import * as React from "react"
import { useId, useMemo } from "react"
import { useId, useMemo, useCallback } from "react"
import {
PresenceContext,
PresenceContextProps,
Expand Down Expand Up @@ -32,21 +32,26 @@ export const PresenceChild = ({
const presenceChildren = useConstant(newChildrenMap)
const id = useId()

const memoizedOnExitComplete = useCallback(
(childId: string) => {
presenceChildren.set(childId, true)

for (const isComplete of presenceChildren.values()) {
if (!isComplete) return // can stop searching when any is incomplete
}

onExitComplete && onExitComplete()
},
[presenceChildren, onExitComplete]
)

const context = useMemo(
(): PresenceContextProps => ({
id,
initial,
isPresent,
custom,
onExitComplete: (childId: string) => {
presenceChildren.set(childId, true)

for (const isComplete of presenceChildren.values()) {
if (!isComplete) return // can stop searching when any is incomplete
}

onExitComplete && onExitComplete()
},
onExitComplete: memoizedOnExitComplete,
register: (childId: string) => {
presenceChildren.set(childId, false)
return () => presenceChildren.delete(childId)
Expand All @@ -57,7 +62,9 @@ export const PresenceChild = ({
* we want to make a new context value to ensure they get re-rendered
* so they can detect that layout change.
*/
presenceAffectsLayout ? [Math.random()] : [isPresent]
presenceAffectsLayout
? [Math.random(), memoizedOnExitComplete]
: [isPresent, memoizedOnExitComplete]
)

useMemo(() => {
Expand Down

0 comments on commit 6b27a80

Please sign in to comment.