2

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.

Nyi Nyi Hmue Aung
  • 587
  • 1
  • 7
  • 19
  • Can you explain a little bit more what are you trying to achieve? – Gulshan Aggarwal Jun 10 '22 at 05:31
  • I have one custom hook that returns 2 react components. So that the components can be displayed wherever I am calling the custom hook. It works fine and I can achieve what I want. But, I have heard that returning react components inside custom hook is not a good practice. So, I am sort of looking for an alternative that will work the same way without returning components inside custom hook. – Nyi Nyi Hmue Aung Jun 10 '22 at 05:36

1 Answers1

1

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
dbuchet
  • 1,561
  • 1
  • 5
  • 7
  • That is a great idea. But, how about the other states I need to return to the parent component? I have a lot of states and functions that must be returned to the parent component. Since, your idea is to create React component, we can't return anything else apart from JSX. Can you also think of a better way to do that?? Thanks, anyway – Nyi Nyi Hmue Aung Jun 11 '22 at 12:38
  • So your hook must return the `myCustomProp` to be passed de `MyComponent`. So your parent component can use this hook, with everything you need, and your hook also return anything needed to be passed to `MyComponent`. – dbuchet Jun 11 '22 at 21:59