Skip to content

Commit

Permalink
refactor: make ref stable (#62)
Browse files Browse the repository at this point in the history
* refactor: make ref stable

* chore: useMemo instead
  • Loading branch information
zombieJ authored Feb 11, 2025
1 parent 538b35f commit 4dd7ad1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
27 changes: 22 additions & 5 deletions src/CSSMotion.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,13 @@ export function genCSSMotion(config: CSSMotionConfig) {
return getDOM(nodeRef.current) as HTMLElement;
}

const [status, statusStep, statusStyle, mergedVisible] = useStatus(
const [getStatus, statusStep, statusStyle, mergedVisible] = useStatus(
supportMotion,
visible,
getDomElement,
props,
);
const status = getStatus();

// Record whether content has rendered
// Will return null for un-rendered even when `removeOnLeave={false}`
Expand All @@ -162,10 +163,26 @@ export function genCSSMotion(config: CSSMotionConfig) {
}

// ====================== Refs ======================
React.useImperativeHandle(ref, () => ({
nativeElement: getDomElement(),
inMotion: () => status !== STATUS_NONE,
}));
const refObj = React.useMemo<CSSMotionRef>(() => {
const obj = {} as CSSMotionRef;
Object.defineProperties(obj, {
nativeElement: {
enumerable: true,
get: getDomElement,
},
inMotion: {
enumerable: true,
get: () => {
return () => getStatus() !== STATUS_NONE;
},
},
});
return obj;
}, []);

// We lock `deps` here since function return object
// will repeat trigger ref from `refConfig` -> `null` -> `refConfig`
React.useImperativeHandle(ref, () => refObj, []);

// ===================== Render =====================
let motionChildren: React.ReactNode;
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export default function useStatus(
onLeaveEnd,
onVisibleChanged,
}: CSSMotionProps,
): [MotionStatus, StepStatus, React.CSSProperties, boolean] {
): [() => MotionStatus, StepStatus, React.CSSProperties, boolean] {
// Used for outer render usage to avoid `visible: false & status: none` to render nothing
const [asyncVisible, setAsyncVisible] = useState<boolean>();
const [getStatus, setStatus] = useSyncState<MotionStatus>(STATUS_NONE);
Expand Down Expand Up @@ -294,5 +294,5 @@ export default function useStatus(
};
}

return [currentStatus, step, mergedStyle, asyncVisible ?? visible];
return [getStatus, step, mergedStyle, asyncVisible ?? visible];
}

0 comments on commit 4dd7ad1

Please sign in to comment.