I'm building a <BasicForm>
component that will be used to build forms inside my application. It should handle submit, validation and also should keep track of the inputs state (like touched, dirty, etc).
Therefore, it needs some functions to do all that and I've been wondering what is the best place to put those declarations (concerning code organization and performance optimization, considering React and JavaScript best practices).
I'm using React 16.8 hooks and bundling with Webpack.
So far, here's what I've got:
BasicForm.js
/* I moved those validating functions to a different file
because I thought they are helpers and not directly related
to my BasicForm functionality */
import { validateText, validatePassword, validateEmail } from './Parts/ValidationHelpers';
function BasicForm(props) {
const [inputs, setInputs] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
// These are functions to handle these events
function onChange(event) {...}
function onBlur(event) {...}
function onFocus(event) {...}
// This function creates the initial state for each form input
function setInputInitialState(inputProps) {...}
// This functions does what it name says
function validateAllFields() {...}
// This one also
function checkValidationAndSubmit() {...}
return(
<FormContext.Provider value={{
onBlur: onBlur,
onFocus: onFocus,
onChange: onChange,
inputs: inputs,
setInputInitialState: setInputInitialState
}}>
<form onSubmit={onSubmit} method='POST' noValidate>
{props.children}
</form>
</FormContext.Provider>
);
}
My question is: as you can see, up to this point, I'm declaring all the functions that my <BasicForm>
uses (onChange
, onBlur
, onFocus
, setInputInitialState
, validateAllFields
, checkValidationAndSubmit
) inside the body of my BasicForm
React component function.
Is this the best practice? If I was using classes those functions would probably be methods of my BasicForm
class. But since I changed to hooks and got rid of most classes, I always have doubts about placing auxiliar functions inside or outside my React components function's body. Is there a best practice for this?
When the auxiliar function may need some variables or state from my main function, I could always pass them as parameters when I call them (if they are declared outside).
Do I gain or lose anything if I declare them outside of my BasicForm
function? Keeping in mind that this is a module that gets bundled with Webpack.