Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Functional sub component best practice

Is there a best practice between using a constant or a sub-component in React functional components?

See the simple example below: in the return() function, {warningConst} and <WarningFunc /> will produce the same result, but I’m not sure which one is the best to use.

    function WarningDialog(props) {
    
    //As constant
    const warningConst = <>Warning {props.message}</>
    
    //As functional component
    function WarningFunc(props) {
        return (
            <>Warning {props.message}</>
        )
    }
    
    return (
        {warningConst}
        <WarningFunc message={props.message} />
    )
}

Of course this example is very simple, but I sometimes have long return() which I would like to split to make the code more readable. And I’m not sure if I should create sub-components or simply use constants.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is your opinion about this?

>Solution :

They are different things.

  • One is a variable which can refer to JSX. It isn’t a component, e.g. doesn’t have life cycle of its own. You can use it if it improves readability for you.
  • Another one is a component. But: declaring component within the function is not recommended (as you did with WarningFunc). Put its definition outside WarningDialog. Reason is reconciliation algorithm. When component is defined within another component, the "constructor" function is different each time because it is recreated, and reconciliation algorithm may think the component type is different each time.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading