This is two React components source code coding styles (put your attention on onSubmit):
Version 1:
...
const ContactsEditPage = ({ match }) => {
...
const [updateContact] = useMutation(
gql`mutation updateContactById ($id: UUID!, $input: ContactPatch!) {
updateContactById(input: {id: $id, contactPatch: $input}) {
clientMutationId
}
}`
);
return (
...
<Formik
initialValues={data.contactById}
onSubmit={(values, actions) => {
updateContact({
variables: {
id: match.params.contactId,
input: values
}
})
.then(() => history.push('./'));
}}
>
<Form>
<FieldGroup>
<FieldRow>
<FieldLabel>Email:</FieldLabel>
<FieldInput
as={Field}
type='email'
name='email'
placeholder='Email'
/>
...
);
};
Version 2:
...
const ContactsEditPage = ({ match }) => {
...
const [updateContact] = useMutation(
gql`mutation updateContactById ($id: UUID!, $input: ContactPatch!) {
updateContactById(input: {id: $id, contactPatch: $input}) {
clientMutationId
}
}`
);
function handleContactSubmit(values) {
updateContact({
variables: {
id: match.params.contactId,
input: values
}
})
.then(() => history.push('./'))
}
return (
...
<Formik
initialValues={data.contactById}
onSubmit={handleContactSubmit}
>
<Form>
<FieldGroup>
<FieldRow>
<FieldLabel>Email:</FieldLabel>
<FieldInput
as={Field}
type='email'
name='email'
placeholder='Email'
/>
...
);
};
The differences:
- version 1 use inline Javascript code in event handler attribute
onSubmit - version 2 use
handleContactSubmitfunction instead inline Javascript code
In the first part of my coding life, I preferred to use handler function (version 2).
Now I have a preference for inline code (version 1) when:
- this code isn't too long
- and this code is used only once
Why: I prefer inline event handler code to avoid indirection in code to improve human readability (for coding review process).
There is also a cost to use a function (inderection). When a new reader encounters this code, they need to jump between many function definitions in many files. This non-linear reading process requires more mental focus than reading linear code.
I meet a majority of ReactJS coders who prefer to use handler function (produce indirection in code).
My question:
- Am I part of a coder minority who prefer indirection in code?
- Do I have to accept majority preference even if my non-linear reading process requires more mental focus than reading linear code? And add handler function rule use in the ReactJS style guide in my project?
Note:
Best regards,
Stéphane