Skip to content

Commit c07d12e

Browse files
authored
Merge pull request #3752 from motiondivision/fix-3746-animatepresence-strictmode-remount
Fix AnimatePresence remounting present children inside React.StrictMode (#3746)
2 parents bbabb00 + b497f1d commit c07d12e

4 files changed

Lines changed: 215 additions & 5 deletions

File tree

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import { AnimatePresence, motion } from "framer-motion"
2+
import { useEffect, useRef, useState } from "react"
3+
4+
/**
5+
* Reproduction for #3746.
6+
*
7+
* A bar chart with two datasets that share a key ("persist"). Switching
8+
* datasets should translate the persisting bar to its new position. It should
9+
* never replay its enter animation (width from 0) and never re-mount.
10+
*
11+
* The reported bug appears on the *second* switch, under React.StrictMode
12+
* (dev/react already renders every test inside StrictMode).
13+
*/
14+
15+
interface Datum {
16+
id: string
17+
value: number
18+
color: string
19+
}
20+
21+
const datasetA: Datum[] = [
22+
{ id: "a", value: 120, color: "blue" },
23+
{ id: "persist", value: 200, color: "red" },
24+
{ id: "b", value: 160, color: "green" },
25+
]
26+
27+
const datasetB: Datum[] = [
28+
{ id: "c", value: 140, color: "purple" },
29+
{ id: "d", value: 180, color: "orange" },
30+
{ id: "persist", value: 240, color: "red" },
31+
]
32+
33+
interface PresenceDatasetState {
34+
mounts: Record<string, number>
35+
resetWidths: () => void
36+
minWidth: () => number
37+
}
38+
39+
declare global {
40+
interface Window {
41+
presenceDataset: PresenceDatasetState
42+
}
43+
}
44+
45+
/**
46+
* Sample the persisting bar every frame so the spec can assert it never
47+
* collapsed towards 0, rather than catching it at a single lucky moment.
48+
*/
49+
const widths: number[] = []
50+
51+
const state: PresenceDatasetState = {
52+
mounts: {},
53+
resetWidths: () => {
54+
widths.length = 0
55+
},
56+
minWidth: () => (widths.length ? Math.min(...widths) : -1),
57+
}
58+
59+
window.presenceDataset = state
60+
61+
function Bar({ id, value, color }: Datum) {
62+
useEffect(() => {
63+
state.mounts[id] = (state.mounts[id] || 0) + 1
64+
}, [])
65+
66+
return (
67+
<motion.div
68+
layout
69+
id={`bar-${id}`}
70+
initial={{ width: 0 }}
71+
animate={{ width: value }}
72+
exit={{ width: 0 }}
73+
transition={{ duration: 0.4, ease: "linear" }}
74+
style={{
75+
height: 40,
76+
marginBottom: 8,
77+
background: color,
78+
}}
79+
/>
80+
)
81+
}
82+
83+
export function App() {
84+
const [data, setData] = useState(datasetA)
85+
const raf = useRef(0)
86+
87+
useEffect(() => {
88+
const sample = () => {
89+
const el = document.getElementById("bar-persist")
90+
if (el) widths.push(el.getBoundingClientRect().width)
91+
raf.current = requestAnimationFrame(sample)
92+
}
93+
raf.current = requestAnimationFrame(sample)
94+
return () => cancelAnimationFrame(raf.current)
95+
}, [])
96+
97+
return (
98+
<div>
99+
<button
100+
id="switch"
101+
onClick={() =>
102+
setData((d) => (d === datasetA ? datasetB : datasetA))
103+
}
104+
>
105+
Switch dataset
106+
</button>
107+
<div style={{ position: "relative" }}>
108+
<AnimatePresence>
109+
{data.map((datum) => (
110+
<Bar key={datum.id} {...datum} />
111+
))}
112+
</AnimatePresence>
113+
</div>
114+
</div>
115+
)
116+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Reproduction for #3746 — a key present in both datasets must not be treated
3+
* as freshly entering when the dataset is switched.
4+
*
5+
* The reported symptom is that on the *second* switch the persisting bar
6+
* "disappears and reappears, and its width animates from 0". We sample its
7+
* width every frame for the whole switch, so a collapse can't be missed
8+
* between assertions.
9+
*/
10+
describe("AnimatePresence dataset switch", () => {
11+
it("Never replays the enter animation for a persisting key", () => {
12+
cy.visit("?test=animate-presence-strict-dataset")
13+
.wait(700)
14+
// First switch A -> B, let it settle completely.
15+
.get("#switch")
16+
.trigger("click", 5, 5, { force: true })
17+
.wait(700)
18+
// Start sampling fresh, then perform the second switch.
19+
.window()
20+
.then((win: any) => win.presenceDataset.resetWidths())
21+
.get("#switch")
22+
.trigger("click", 5, 5, { force: true })
23+
.wait(700)
24+
.window()
25+
.then((win: any) => {
26+
// The bar goes from 240 -> 200. It must never dip towards 0.
27+
expect(win.presenceDataset.minWidth()).to.be.greaterThan(150)
28+
// And it must never have re-mounted. StrictMode double-invokes
29+
// effects on mount, so a bar that mounts once reports 2.
30+
expect(win.presenceDataset.mounts.persist).to.equal(2)
31+
})
32+
})
33+
})

‎packages/framer-motion/src/components/AnimatePresence/__tests__/AnimatePresence.test.tsx‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -770,6 +770,58 @@ describe("AnimatePresence", () => {
770770

771771
expect(opacity.get()).toBe(1)
772772
})
773+
774+
test("Exiting children don't reorder present children (#3746)", async () => {
775+
const Component = ({ ids }: { ids: string[] }) => (
776+
<AnimatePresence>
777+
{ids.map((id) => (
778+
<motion.div
779+
key={id}
780+
data-id={id}
781+
initial={{ opacity: 0 }}
782+
animate={{ opacity: 1 }}
783+
exit={{ opacity: 0 }}
784+
transition={{ duration: 10 }}
785+
/>
786+
))}
787+
</AnimatePresence>
788+
)
789+
790+
const { container, rerender } = render(
791+
<Component ids={["a", "persist", "b"]} />
792+
)
793+
794+
await act(async () => {
795+
await nextFrame()
796+
})
797+
798+
const persist = container.querySelector('[data-id="persist"]')
799+
800+
// "a" and "b" exit, "c" and "d" enter, "persist" stays.
801+
await act(async () => {
802+
rerender(<Component ids={["c", "d", "persist"]} />)
803+
})
804+
await act(async () => {
805+
await nextFrame()
806+
})
807+
808+
const order = Array.from(container.querySelectorAll("[data-id]")).map(
809+
(el) => el.getAttribute("data-id")
810+
)
811+
812+
/**
813+
* Each exiting child should hold its place relative to the children it
814+
* sat between: "a" led the list, "b" followed "persist". Exiting
815+
* children used to be spliced in at their index within the *previously*
816+
* rendered children, which indexes into the wrong list and interleaved
817+
* them with the entering children — ["a", "c", "b", "d", "persist"].
818+
*/
819+
expect(order.indexOf("a")).toBe(0)
820+
expect(order.indexOf("b")).toBeGreaterThan(order.indexOf("persist"))
821+
822+
// And the persisting child must be the same element, never remounted.
823+
expect(container.querySelector('[data-id="persist"]')).toBe(persist)
824+
})
773825
})
774826

775827
describe("AnimatePresence with custom components", () => {

‎packages/framer-motion/src/components/AnimatePresence/index.tsx‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -134,14 +134,23 @@ export const AnimatePresence = ({
134134
/**
135135
* Loop through all the currently rendered components and decide which
136136
* are exiting.
137+
*
138+
* Exiting children are reinserted directly after the child they
139+
* previously followed. Splicing at their index within the previously
140+
* rendered children, as we used to, indexes into the wrong list: it
141+
* can interleave them with entering children and push present children
142+
* to new positions, remounting them (#3746).
137143
*/
138-
for (let i = 0; i < renderedChildren.length; i++) {
139-
const child = renderedChildren[i]
140-
const key = getChildKey(child)
144+
let insertionIndex = 0
141145

142-
if (!presentKeys.includes(key)) {
143-
nextChildren.splice(i, 0, child)
146+
for (const child of renderedChildren) {
147+
const presentIndex = presentKeys.indexOf(getChildKey(child))
148+
149+
if (presentIndex === -1) {
150+
nextChildren.splice(insertionIndex++, 0, child)
144151
exitingChildren.push(child)
152+
} else {
153+
insertionIndex = presentIndex + exitingChildren.length + 1
145154
}
146155
}
147156

0 commit comments

Comments
 (0)