How to preview uploaded image in React

Showing image previews before upload significantly improves user experience by letting users verify their selection instantly. As the creator of CoreUI with over 11 years of React development experience since 2014, I’ve implemented image preview functionality in countless profile editors and galleries. The most effective solution is to use URL.createObjectURL() to create a temporary URL for the selected file. This approach is fast, efficient, and works seamlessly without reading the entire file into memory.

Use URL.createObjectURL() to preview images before upload in React.

const [preview, setPreview] = useState(null)
const [file, setFile] = useState(null)

const handleFileChange = (e) => {
  const selectedFile = e.target.files[0]
  if (selectedFile && selectedFile.type.startsWith('image/')) {
    setFile(selectedFile)
    const objectUrl = URL.createObjectURL(selectedFile)
    setPreview(objectUrl)
  }
}

useEffect(() => {
  return () => {
    if (preview) {
      URL.revokeObjectURL(preview)
    }
  }
}, [preview])

return (
  <div>
    <input type='file' accept='image/*' onChange={handleFileChange} />
    {preview && <img src={preview} alt='Preview' style={{maxWidth: '300px'}} />}
  </div>
)

The file input’s onChange handler checks if the selected file is an image using type.startsWith('image/'). URL.createObjectURL() creates a temporary URL pointing to the file blob, which can be used directly as an image source. The useEffect cleanup function revokes the object URL when the component unmounts or a new image is selected, preventing memory leaks. The accept attribute restricts file selection to images only.

Best Practice Note

This is the same image preview pattern we use in CoreUI React components for optimal performance. Always revoke object URLs with URL.revokeObjectURL() to free memory. For displaying multiple image previews, map through an array of object URLs and remember to revoke each one in the cleanup function.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
JavaScript printf equivalent
JavaScript printf equivalent

How to Use Bootstrap Dropdown in Angular – CoreUI Integration Guide
How to Use Bootstrap Dropdown in Angular – CoreUI Integration Guide

How to Convert a Map to an Array in JavaScript
How to Convert a Map to an Array in JavaScript

How to Open All Links in New Tab Using JavaScript
How to Open All Links in New Tab Using JavaScript

Answers by CoreUI Core Team