Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenmori/f4c89dbf7b09ed081b9160bf36af34b9 to your computer and use it in GitHub Desktop.
Save kenmori/f4c89dbf7b09ed081b9160bf36af34b9 to your computer and use it in GitHub Desktop.
Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

これがでたあなた。 恐らく 原因はmapで回すrender関数とHooksの相性が悪いことのような気がしています

facebook/react#14250 (comment)

JSX内で関数を使うと、その中ではHooksは使えません。

render関数を使っているところを疑ってください。

このようなところです。

// コードは適当です
const render = (props) => ((item, index) => {
const callback = useCallback(props.callback, [])
const memo = useMemo(some...)
                return (
                <Component
                    key={item.id}
                    label={item.name}
                    onClick={createClickButtonDom(props.onClickItem, item.name)}
                    width={item.width}
                    active={}
                />)
            }
        )
}
export const Component = React.memo<Props>(props => 
    <Wrap>
        {props.items.map(render(props))}
    </Wrap>
))

コールバックを使うパターンだと

this is ok.

const renderTabButton = (
    activeTabIndex: number,
    onClickItem: (itemName: string) => void
) => (item: TabItem, index: number): React.ReactElement => {
    const isItemActive = index === activeTabIndex
    const clickButtonDom = createClickButtonDom(onClickItem, item.name)

    return (
        <Component
            key={item.id}
            label={item.name}
            onClick={clickButtonDom}
            width={item.width}
            active={isItemActive}
        />
    )
}

or

export const Component = React.memo<Props>(props => 
   <Wrap>
       {props.items.map((item, index) => 
               <Component
                   key={item.id}
                   label={item.name}
                   onClick={createClickButtonDom(props.onClickItem, item.name)}
                   width={item.width}
                   active={index === props.activeTabIndex}
               />
       )}
   </Wrap>
))

``

これだけでも消し去れます。(useMemo, useCallbackのどちらか一つでも残っているとダメです)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment