I am implementing an attachment component and trying to be a good citizen by calling URL.revokeObjectURL() when my component is unmounted to cleanup the local blob resources.
Using a class component I would have just used ComponentWillUnmount and I assume that would have worked fine. Now that I am using a functional component I need to use a useEffect hook that has a cleanup function which invokes the URL.revokeObjectUrl method. This was my first approach
useEffect(() => {
return () => {
attachments &&
attachments.forEach((a) => {
console.log('cleaning', a.uri);
URL.revokeObjectURL(a.uri);
});
};
});
but the attachment prop was undefined; I have read this is because its value is set from when the component is first rendered. So I tried to add the props to the array of dependencies
useEffect(() => {
return () => {
attachments &&
attachments.forEach((a) => {
console.log('cleaning', a.uri);
URL.revokeObjectURL(a.uri);
});
};
}, [attachments]);
but then it runs the cleanup code whenever a new attachment is uploaded as the attachments object updates.
What is the right way to implement useEffect so that it only cleans up once when the component is unmounted? I found this SO article but wasn't too happy with the solution and thought there must be a better way