URL.createObjectURL(objectUrl)
blob 객체를 가리키는 URL을 만들어 준다. URL은 자신을 생성한 브라우저의 창이 닫히면 무효화된다.
URL.revokeObjectURL(objectUrl)
createObjectURL로 생성한 URL을 해제한다. URL을 더는 쓸 일이 없을 때, 브라우저에게 해당 객체를 더 이상 기억할 필요없다고 알려주는 것이다.
import React, { useEffect, useRef, useState } from "react"
const App = () => {
const [userPhoto, setUserPhoto] = useState<string[]>([])
let photoUrl: string | undefined
useEffect(() => {
// 언마운트 시 url 무효화
return () => {
if (photoUrl !== undefined){
URL.revokeObjectURL(photoUrl)
}
}
}, [photoUrl])
const handleUploadPhoto = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files){
return
}
const blob = new Blob([e.target.files[0]], {type: "image/png"})
photoUrl = URL.createObjectURL(blob)
setUserPhoto([...userPhoto, photoUrl])
}
return (
<div>
{userPhoto.map((photo, index) => (
<div key={index}>
<img src={photo} alt="" />
</div>
))}
<input type="file" onChange={handleUploadPhoto} />
</div>
)
}
export default App