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?
CodePudding user response:
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.
CodePudding user response:
There is basically no affect in performance whether you declare a React functional component with const
or function
.
But declaring a component with function
do have the benefit of hoisting the function to the top of current scope.
I would also suggest putting the "sub-component" outside the current component since "sub-component" is really not a thing.
If you want to detach a part of a large component to make the code clearer, while not making it a child component that have state-wise connection with the current component, put it outside helps you better.