skip to Main Content

I have a component with tabs say TabA and TabB. Each of them has a table who’s data changes depending on which tab the user is at.

Now to get this functionality there are two approaches to it. Either i can use a onClick handler on the tab and set the data. Or on click of the tab i can set the active tab in a state and then use a useEffect to update the data.

With onClick handler

const MyComponent = () => {
    const handleClick  =() => {
        // set active tab and setData depending upon which tab is pressed
    }
    return <>
        <TabHeader>
            <TabTitle onClick={handleClick}>TabA</TabTitle>
            <TabTitle onClick={handleClick}>TabB</TabTitle>
        </TabHeader>
        <TabContent>
            <MyTable data={data}></MyTable>
        </TabContent>
    </>
}

With useEffect

const MyComponent = () => {
    useEffect(() => {
        // set data here
    }, [activetab])
    const handleClick  = () => {
        // set active tab
    }
    return <>
        <TabHeader>
            <TabTitle onClick={handleClick}>TabA</TabTitle>
            <TabTitle onClick={handleClick}>TabB</TabTitle>
        </TabHeader>
        <TabContent>
            <MyTable data={data}></MyTable>
        </TabContent>
    </>
}

I am aware of how to do it. But which one of these is a better solution?

2

Answers


  1. I would suggest to just use the onClick handler rather than have it in useEffect.

    With this, you can just simplify the pattern. In beta.reactjs doc, they also provide a good documentation of when to use useEffect and when not.

    reference: https://beta.reactjs.org/learn/you-might-not-need-an-effect

    Login or Signup to reply.
  2. If you have no other functionality then you shoul use onClick handler.

    useEffect will render the table with empty list. Then it will render with the dependent data.

    But it totally depend on the requirement of the application.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search