Skip to content
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

refactor: optimize AnimatedList component #334

Merged
merged 2 commits into from
Nov 15, 2024
Merged
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
27 changes: 16 additions & 11 deletions registry/default/magicui/animated-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,31 @@ export interface AnimatedListProps {
export const AnimatedList = React.memo(
({ className, children, delay = 1000 }: AnimatedListProps) => {
const [index, setIndex] = useState(0);
const childrenArray = React.Children.toArray(children);
const childrenArray = useMemo(
() => React.Children.toArray(children),
[children],
);

useEffect(() => {
const interval = setInterval(() => {
setIndex((prevIndex) => (prevIndex + 1) % childrenArray.length);
}, delay);
if (index < childrenArray.length - 1) {
const timeout = setTimeout(() => {
setIndex((prevIndex) => prevIndex + 1);
}, delay);

return () => clearInterval(interval);
}, [childrenArray.length, delay]);
return () => clearTimeout(timeout);
}
}, [index, delay, childrenArray.length]);

const itemsToShow = useMemo(
() => childrenArray.slice(0, index + 1).reverse(),
[index, childrenArray],
);
const itemsToShow = useMemo(() => {
const result = childrenArray.slice(0, index + 1).reverse();
return result;
}, [index, childrenArray]);

return (
<div className={`flex flex-col items-center gap-4 ${className}`}>
<AnimatePresence>
{itemsToShow.map((item) => (
<AnimatedListItem key={(item as ReactElement).key}>
<AnimatedListItem key={(item as React.ReactElement).key}>
{item}
</AnimatedListItem>
))}
Expand Down