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

Optimize children flattening #156

Merged
merged 1 commit into from
Aug 12, 2023
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
36 changes: 27 additions & 9 deletions src/react/utils.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,37 @@
import { Children, ReactElement, ReactFragment, ReactNode } from "react";
import { ReactElement, ReactFragment, ReactNode } from "react";
import { exists } from "../core/utils";

export const refKey = "current";

export const emptyComponents = {};

export const flattenChildren = (children: ReactNode) => {
const arr: (ReactElement | ReactFragment | string | number)[] = [];
Children.forEach(children, (e) => {
if (!exists(e) || typeof e === "boolean") {
return;
type ItemElement = ReactElement | ReactFragment | string | number;

const forEach = (children: ReactNode, elements: ItemElement[]) => {
if (Array.isArray(children)) {
for (const c of children) {
forEach(c, elements);
}
arr.push(e);
});
return arr;
} else if (!exists(children) || typeof children === "boolean") {
// filter out, that is the same as React.Children.toArray
} else {
elements.push(children);
}
};

// Relace React.Children.forEach with our tiny implementation.
// In our usage, just flatten children array keeping element instances and their keys, React.Children is redundant and slow.
//
// - React.Children.toArray is slow because it clones element instance.
// - React.Children.map is slow because it clones element instance.
// - React.Children.forEach is slow because it escapes and modifies keys even if they are unused.
//
// And React.Children seems to be in maintenance mode so it's unlikely it would be improved and ported to older versions.
// https://github.com/reactjs/rfcs/pull/61#issuecomment-584402735
export const flattenChildren = (children: ReactNode): ItemElement[] => {
const elements: ItemElement[] = [];
forEach(children, elements);
return elements;
};

export type MayHaveKey = { key?: React.Key };
Loading