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

fix(performance): auto memoize TabList #1449

Merged
merged 1 commit into from
Nov 1, 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
14 changes: 3 additions & 11 deletions src/core/components/tab/tabList.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {cloneElement, forwardRef, useCallback, useMemo, useState} from 'react'
import {cloneElement, forwardRef, useCallback, useState, Children, isValidElement} from 'react'
import {styled} from 'styled-components'
import {Inline, InlineProps} from '../../primitives'

Expand All @@ -9,10 +9,6 @@ export interface TabListProps extends Omit<InlineProps, 'as' | 'height'> {
children: Array<React.ReactElement | null | undefined | false>
}

function _isReactElement(node: unknown): node is React.ReactElement {
return Boolean(node)
}

//Limits the width of tabs in tablist
const CustomInline = styled(Inline)`
& > div {
Expand All @@ -33,22 +29,18 @@ export const TabList = forwardRef(function TabList(
const {children: childrenProp, ...restProps} = props
const [focusedIndex, setFocusedIndex] = useState(-1)

const children = useMemo(() => childrenProp.filter(_isReactElement), [childrenProp])
const children: React.ReactElement[] = Children.toArray(childrenProp).filter(isValidElement)

const tabs = children.map((child, childIndex) =>
cloneElement(child, {
focused: focusedIndex === childIndex,
key: childIndex,
onFocus: () => handleTabFocus(childIndex),
onFocus: () => setFocusedIndex(childIndex),
}),
)

const numTabs = tabs.length

const handleTabFocus = useCallback((tabIdx: number) => {
setFocusedIndex(tabIdx)
}, [])

const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'ArrowLeft') {
Expand Down
Loading