diff --git a/src/Box.tsx b/src/Box.tsx index 8ce17a7..5f96931 100644 --- a/src/Box.tsx +++ b/src/Box.tsx @@ -194,18 +194,24 @@ function BoxImpl( setYogaProperties(node, flexProps, scaleFactor) }, [flexProps, node, scaleFactor]) - // Make child known to the parents yoga instance *before* it calculates layout useLayoutEffect(() => { - if (!group.current || !parent) return - - parent.insertChild(node, parent.getChildCount()) - registerBox(node, group.current, flexProps, centerAnchor) + if (!parent) return // Remove child on unmount return () => { parent.removeChild(node) unregisterBox(node) } + }, [node, parent]) + + // Make child known to the parents yoga instance *before* it calculates layout + useLayoutEffect(() => { + if (!group.current || !parent) return + + if (registerBox(node, group.current, flexProps, centerAnchor)) { + //newly registered node: add it to the parent + parent.insertChild(node, parent.getChildCount()) + } }, [node, parent, flexProps, centerAnchor, registerBox, unregisterBox]) // We need to reflow if props change diff --git a/src/Flex.tsx b/src/Flex.tsx index 44d30b4..b43a26c 100644 --- a/src/Flex.tsx +++ b/src/Flex.tsx @@ -225,10 +225,16 @@ function FlexImpl( const registerBox = useCallback( (node: YogaNode, group: THREE.Group, flexProps: R3FlexProps, centerAnchor: boolean = false) => { const i = boxesRef.current.findIndex((b) => b.node === node) + const boxItem = { group, node, flexProps, centerAnchor } if (i !== -1) { - boxesRef.current.splice(i, 1) + //node already contained: update box + boxesRef.current[i] = boxItem + return false + } else { + //node not contained: insert new box + boxesRef.current.push(boxItem) + return true } - boxesRef.current.push({ group, node, flexProps, centerAnchor }) }, [] ) diff --git a/src/context.ts b/src/context.ts index 03c242d..31551c7 100644 --- a/src/context.ts +++ b/src/context.ts @@ -6,7 +6,7 @@ import { R3FlexProps } from './props' export interface SharedFlexContext { scaleFactor: number requestReflow(): void - registerBox(node: YogaNode, group: Group, flexProps: R3FlexProps, centerAnchor?: boolean): void + registerBox(node: YogaNode, group: Group, flexProps: R3FlexProps, centerAnchor?: boolean): boolean unregisterBox(node: YogaNode): void notInitialized?: boolean } @@ -18,6 +18,7 @@ const initialSharedFlexContext: SharedFlexContext = { }, registerBox() { console.warn('Flex not initialized! Please report') + return false }, unregisterBox() { console.warn('Flex not initialized! Please report')