Reputation: 141
I have a function handleFileSelect
inside a React Component. It does some processing on the input file, and based on that it updates some states, which would trigger a rerender of the component.
But rerenders cause the function to be re-created. So will all the previous processed info be lost?
So should I use something like useCallback to prevent re-creation of my function?
And if that is the case, should'nt I do this for most functions?
const handleFileSelect = async(event: ChangeEvent < HTMLInputElement > ) => {
if (event.target.files && event.target.files ? .length > 0) {
setFormDisabled(true); // state-update
const file = event.target.files[0];
if (!imageWithinSizeLimit(file)) {
sendToast('error', 'File size beyond allowed range! Choose a file lesser than 0.5MB')
clearImageInput();
setFormDisabled(false); // state-update
return;
}
const valid = await validateImageType(file);
if (valid) {
const fileReader = new FileReader();
fileReader.readAsDataURL(file)
fileReader.onload = function(ev) {
// @ts-ignore
imagePreviewRef.current ? .setAttribute("src", ev.target.result)
}
setImageValid(true); // state-update
setFormDisabled(false) // state-update
}
else {
clearImageInput();
sendToast('error', "We only accept PNG or JPEG files as Avatar images")
setFormDisabled(false) // state-update
}
}
}
Upvotes: 0
Views: 51
Reputation: 3230
Simple answer: No.
If you don't need to track your function as dependency or you don't create component inside another component, then you don't need useCallback
Upvotes: 1