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.
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 outsideWarningDialog. 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.