Nyi Nyi Hmue Aung
Nyi Nyi Hmue Aung

Reputation: 726

What is the alternative to return component from react custom hook?

I have encountered a situation where I needed to return 2 react components from custom hook. Just to briefly give you the overview, I have one custom hook where all the required states congregate. Inside the custom hook, I also store the 2 components inside variables and pass down the props returned from another custom hook. And I am returning 2 components inside the custom hook. Some developers said it's bad to return react component inside custom hook. So I am lookin for an alternative. Here is the code demonstration.

import FirtComponent from '/'
import SecondComponent from "/"

const useCustomHook =()=> {
  
 const {props} =usePropsHook()
  
const {firstComponentProps,secondComponentProps} =props

 return {firstComponent :<FirstComponent {...firstComponentProps}>,secondComponent :<SecondComponent {...secondCOmponentProps} />} 
 
 
}

I am doing it this way so that I have the flexibility to display these 2 components anywhere I want. Such as next to each other, firstComponent on top and second component in below. FirstComponent next to other modal and things like that.

Upvotes: 1

Views: 1833

Answers (1)

dbuchet
dbuchet

Reputation: 1651

Why don't you just create a new Component, and depending on a prop you render Component1 or Component2?

import FirstComponent from '/'
import SecondComponent from "/"

const MyComponent = ({myCustomProp}) => {
  
    const { props } = usePropsHook()

    const { firstComponentProps, secondComponentProps } =props

    if (myCustomProp) return <FirstComponent {...firstComponentProps} />

    return <SecondComponent {...secondComponentProps} />
}

Then you can use this component like

<MyComponent myCustomProp />    // render FirstComponent
<MyComponent />                 // render SecondComponent

Upvotes: 1

Related Questions