Search code examples
reactjstypescriptnext.jsreact-hooks

TypeScript NextJS: Rendered fewer hooks than expected


I followed all the react hook rules, and I still can't figure out how this is rendering fewer hooks than expected, the hooks that aren't there are set into child components.

React tells me it's the 16th line of my Tab.tsx so here is my whole tab.tsx

"use client";
import React, { useState } from 'react';
import Content from './ItemsContent';
import Feedback from './Feedback';

export default function Tab(props: { tabs: string[] }) {
    const [active, setActive] = useState(0); // Initialize active state with 0
    const [content, setContent] = useState(Content); // Initialize content state with the first tab content
    const possibleContent = [Content, Feedback]; // Add all tabs

    const changeTab = (index: number) => {
        if (possibleContent.length > index) {
            setActive(index); // Set current tab index for css
            setContent(possibleContent[index]); // Set content to tabs content
        }
        else {
            // notification that the content is not available
        }
    }

    return (
        <div className="w-full pt-4 h-full bg-[rgb(15,15,15)] rounded-t-xl">
            <div className="flex justify-around">
                {props.tabs.map((tab, index) => {
                    return (
                        <div key={index} onClick={() => changeTab(index)} className={`text-center text-lg cursor-pointer ${index === active ? 'bg-[rgb(25,25,25)]' : 'hover:bg-[rgb(25,25,25)]'} ${possibleContent.length > index ? '' : 'text-slate-700'} px-4 pb-2 pt-2 rounded-t-lg`}>
                            {tab}
                        </div>
                    )
                })}
            </div>
            {content}
        </div>
    )
}

I am only calling the functions inside the change tab function, I really don't see how it could error.

I don't see the issue, I expect it to work just fine, the setActive needs to set the number of the active tab, then the content needs to load the appropriate tab.


Solution

  • This error is received when you might be returning react components inside a condition. for example:

    if(condition){
     return <A />
    }else{
     return null;
    }
    

    This will give an error, replace it with

    if(condition){
     return <A />
    }else{
     return <></>;
    }
    

    i.e make sure number of compnents returned by any function should always be same.