I have a React code that lets you add image files, preview, delete on click and add more. I’m happy with the functionality but I noticed some performance issues.
function App() {
const [selectedFiles, setSelectedFiles] = React.useState([])
function GenerateGuid() {
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c => {
const randomValue = crypto.getRandomValues(new Uint8Array(1))[0];
const shiftedValue = (randomValue & 15) >> (+c / 4);
return shiftedValue.toString(16);
});
}
const handleImageDelete = (id) => {
const updatedFiles = selectedFiles.filter((file) => file.id !== id);
setSelectedFiles(updatedFiles);
};
const handleChange = (e) => {
const files = Array.from(e.target.files)
const filesObject = files.map(file => {
return (
{ id: GenerateGuid(), fileObject: file }
)
})
setSelectedFiles([...selectedFiles, ...filesObject])
}
return (
<div className='App'>
<h1>Hello React.</h1>
<h2>Start editing to see some magic happen!</h2>
<input type="file" onChange={handleChange} multiple />
{selectedFiles.map(
(file, index) => {
return (
<img
key={file.id}
onClick={() => handleImageDelete(file.id)}
style={{ height: "5rem", backgroundColor: "black" }}
src={URL.createObjectURL(file.fileObject)}
alt={"training spot"}
/>
)
}
)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Works fine in small file amounts, but let’s review the following scenario.
- Add 10 images each ~2MB size, so we’ve uploaded ~20MB of data
- Click on one image to delete it
- 9 images re-render and network tab shows 9 images reloaded again, so 19 requests in total to complete this operation.
Is there a clever way to prevent remaining images from reloading?
So far just testing in the sandbox and looking for solution.