Skip to content

fix: instance children array would desync from object children array #3490

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions packages/fiber/src/core/reconciler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,14 @@ function handleContainerEffects(parent: Instance, child: Instance, beforeChild?:

function appendChild(parent: HostConfig['instance'], child: HostConfig['instance'] | HostConfig['textInstance']) {
if (!child) return

// Link instances
child.parent = parent

// Remove existing child if it exists
const existingIndex = parent.children.indexOf(child)
if (existingIndex !== -1) parent.children.splice(existingIndex, 1)

// Append child
parent.children.push(child)
Comment on lines -340 to 348
Copy link
Member

@CodyJasonBennett CodyJasonBennett Apr 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#3490 (comment) Maybe we can move the check before mutating anything.

// Remove existing child if it exists (re-order to last)
if (child.parent === parent) {
  const existingIndex = parent.children.indexOf(child)
  if (existingIndex !== -1) parent.children.splice(existingIndex, 1)
}

// Link instances
child.parent = parent

// Append child
parent.children.push(child)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes this makes sense. I think further optimizations would require convincing React to provide a path for append separate from reorder since it has this information internally. However, for now we can probably not worry about this.


// Attach tree once complete
Expand All @@ -355,8 +360,14 @@ function insertBefore(

// Link instances
child.parent = parent
const childIndex = parent.children.indexOf(beforeChild)
if (childIndex !== -1) parent.children.splice(childIndex, 0, child)

// Remove the child if it already exists in the parent's children array
const existingIndex = parent.children.indexOf(child)
if (existingIndex !== -1) parent.children.splice(existingIndex, 1)

// Insert the child at the correct position
const beforeChildIndex = parent.children.indexOf(beforeChild)
if (beforeChildIndex !== -1) parent.children.splice(beforeChildIndex, 0, child)
else parent.children.push(child)

// Attach tree once complete
Expand Down
20 changes: 11 additions & 9 deletions packages/fiber/tests/renderer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -782,12 +782,10 @@ describe('renderer', () => {
})

it('should properly handle array of components with changing keys and order', async () => {
// Component that renders a mesh with a specific ID
const MeshComponent = ({ id }: { id: number }) => {
return <mesh name={`mesh-${id}`} />
}

// Component that maps over an array of values to render MeshComponents
const Test = ({ values }: { values: number[] }) => (
<>
{values.map((value) => (
Expand All @@ -796,24 +794,26 @@ describe('renderer', () => {
</>
)

// Initial render with 4 values
// Initial render with 4 values in ascending order
const initialValues = [1, 2, 3, 4]
const store = await act(async () => root.render(<Test values={initialValues} />))
const { scene } = store.getState()

// Check initial state
expect(scene.children.length).toBe(4)
const initialNames = scene.children.map((child) => child.name).sort()
const initialNames = scene.children.map((child) => child.name)
expect(initialNames).toEqual(['mesh-1', 'mesh-2', 'mesh-3', 'mesh-4'])
expect((scene as any).__r3f.children.length).toBe(4)

// Update with one less value and different order
const updatedValues = [3, 1, 4]
console.log('rendering', updatedValues)
await act(async () => root.render(<Test values={updatedValues} />))

// Check that the scene has exactly the meshes we expect
expect(scene.children.length).toBe(3)
const updatedNames = scene.children.map((child) => child.name).sort()
expect(updatedNames).toEqual(['mesh-1', 'mesh-3', 'mesh-4'])
const updatedNames = scene.children.map((child) => child.name)
expect(updatedNames).toEqual(['mesh-3', 'mesh-1', 'mesh-4'])
expect((scene as any).__r3f.children.length).toBe(3)

// Verify mesh-2 was removed
expect(scene.children.find((child) => child.name === 'mesh-2')).toBeUndefined()
Expand All @@ -824,12 +824,14 @@ describe('renderer', () => {

// Update with different order again
const reorderedValues = [4, 1]
console.log('rendering', reorderedValues)
await act(async () => root.render(<Test values={reorderedValues} />))

// Check final state
expect(scene.children.length).toBe(2)
const finalNames = scene.children.map((child) => child.name).sort()
expect(finalNames).toEqual(['mesh-1', 'mesh-4'])
const finalNames = scene.children.map((child) => child.name)
expect(finalNames).toEqual(['mesh-4', 'mesh-1'])
expect((scene as any).__r3f.children.length).toBe(2)

// Verify mesh-3 was removed
expect(scene.children.find((child) => child.name === 'mesh-3')).toBeUndefined()
Expand Down