I have this piece of code
// This is onChange event
function nameChangeHandler(e, field = 'Name') {
const currentName = e.target.value;
if (currentName.length >= 10) {
if (!errors.some((x) => x.field == field)) {
setErrors((state) => [
...state,
{
field,
errorMessage:
field +
' should be between 3 and 10 characters long',
},
]);
}
} else if (currentName.length <= 3) {
if (!errors.some((x) => x.field == field)) {
setErrors((state) => [
...state,
{
field,
errorMessage:
field +
' should be between 3 and 10 characters long',
},
]);
}
} else {
setErrors((state) => state.filter((x) => x.field !== field));
}
}
This part of the code is redundant
if (!errors.some((x) => x.field == field)) {
setErrors((state) => [
...state,
{
field,
errorMessage:
field +
' should be between 3 and 10 characters long',
},
]);
}
My question is if place it inside an useCallback hook. Will it be a good practice or it's stupid move. Refactored code should be looking something like this:
const errorSetter = useCallback((field) => {
if (!errors.some((x) => x.field == field)) {
setErrors((state) => [
...state,
{
field,
errorMessage:
field + ' should be between 3 and 10 characters long',
},
]);
}
}, []);
function nameChangeHandler(e, field = 'Name') {
const currentName = e.target.value;
if (currentName.length >= 10) {
errorSetter(field)
} else if (currentName.length <= 3) {
errorSetter(field)
} else {
setErrors((state) => state.filter((x) => x.field !== field));
}
}
I tried adding it in useCallback and it works fine. All though, I'm new to React and don't yet know the best practices.