React Image Upload with a Live Preview and Progress
Build an image upload in React with an instant preview, size and type checks, no memory leaks, and a picture that sharpens from blocks of pixels as the upload progresses.
Image uploads have one advantage over every other kind of upload: the person already knows what they are waiting for, because they can see it. A good image uploader uses that. It shows the picture the moment it is chosen, before a single byte has gone to the server, and it makes the wait feel like something happening to the picture instead of a bar filling beside it.
This guide builds that in React and Tailwind CSS: an instant preview with URL.createObjectURL, the cleanup that stops it leaking memory, size and type checks, and a small canvas technique that draws the picture as coarse blocks and sharpens it as the upload progresses. It assumes you already have a function that sends a file and reports progress; the file upload guide shows one built on XMLHttpRequest.
Preview before you upload
You do not need to read the file or send anything to show it. URL.createObjectURL(file) returns a short blob: address that points at the file in memory, and an img can use it as its src immediately.
There is one rule people forget: every object URL holds the file in memory until you release it with URL.revokeObjectURL. Create one per selected image and revoke it when the image is replaced, removed, or the component unmounts.
"use client";
import { useEffect, useState } from "react";
export function usePreview() {
const [preview, setPreview] = useState<{ file: File; url: string } | null>(null);
// Runs when the preview is replaced or cleared, and when the component unmounts.
useEffect(() => {
return () => {
if (preview) URL.revokeObjectURL(preview.url);
};
}, [preview]);
const choose = (file: File | null) =>
setPreview(file ? { file, url: URL.createObjectURL(file) } : null);
return [preview, choose] as const;
}
The object URL is created in the event that chooses the file, not during render, and the effect's cleanup releases the previous one every time the preview changes and when the component unmounts. That keeps the leak impossible as long as the URL only lives in this hook.
Check the image before accepting it
Type and size checks are the same as for any file, with one image-specific addition: the accept="image/*" attribute lets through formats the browser cannot draw, so confirm the image actually decodes.
const MAX_MB = 10;
export async function checkImage(file: File): Promise<string | null> {
if (!file.type.startsWith("image/")) return "Choose an image file";
if (file.size > MAX_MB * 1024 * 1024) return `Too large: ${(file.size / 1048576).toFixed(0)} MB (max ${MAX_MB} MB)`;
try {
await createImageBitmap(file);
} catch {
return "This image cannot be read";
}
return null;
}
createImageBitmap also gives you the width and height if you want to enforce a minimum size, for example for avatars. As always, repeat the checks on the server.
Showing progress on the picture itself
A progress bar under an image is accurate and forgettable. Drawing the image itself in stages is just as accurate and much more pleasant to watch: start with a handful of large blocks, then step through finer and finer ones until the real picture appears at 100%.
The technique is a two-step draw on a canvas. First draw the image into a tiny offscreen canvas, so the browser averages it down to a few pixels across. Then draw that tiny canvas back up to full size with image smoothing switched off, so each of those pixels becomes a hard-edged block.
const LEVELS = [8, 16, 32, 64, 128];
export function drawStage(canvas: HTMLCanvasElement, image: HTMLImageElement, progress: number) {
const context = canvas.getContext("2d");
if (!context) return;
context.clearRect(0, 0, canvas.width, canvas.height);
if (progress >= 1) {
context.imageSmoothingEnabled = true;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
return;
}
const across = LEVELS[Math.min(LEVELS.length - 1, Math.floor(progress * LEVELS.length))];
const small = document.createElement("canvas");
small.width = across;
small.height = Math.max(1, Math.round((across * canvas.height) / canvas.width));
small.getContext("2d")?.drawImage(image, 0, 0, small.width, small.height);
context.imageSmoothingEnabled = false;
context.drawImage(small, 0, 0, canvas.width, canvas.height);
}
Call it from the progress callback and the picture sharpens in five steps. The Math.floor(progress * LEVELS.length) maps 0 to 99% across the levels, and 100% switches to the smooth full image.
The component
This puts the pieces together, with usePreview, checkImage and drawStage from above in the same file or imported. It takes an upload function, previews the chosen image on a canvas that is sized to the picture, and redraws it as progress arrives.
"use client";
import { useEffect, useRef, useState } from "react";
type Props = {
upload: (file: File, onProgress: (progress: number) => void) => Promise<void>;
};
export function ImageUpload({ upload }: Props) {
const canvas = useRef<HTMLCanvasElement>(null);
const image = useRef<HTMLImageElement | null>(null);
const [preview, setPreview] = usePreview();
const [progress, setProgress] = useState(0);
const [message, setMessage] = useState<string | null>(null);
const file = preview?.file ?? null;
const url = preview?.url ?? null;
// Load the preview into an image element once, and size the canvas to the picture.
useEffect(() => {
if (!url || !canvas.current) return;
const element = new Image();
element.onload = () => {
image.current = element;
const target = canvas.current;
if (!target) return;
const scale = Math.min(1, 640 / element.naturalWidth);
target.width = Math.round(element.naturalWidth * scale);
target.height = Math.round(element.naturalHeight * scale);
drawStage(target, element, 0);
};
element.src = url;
}, [url]);
// Redraw whenever progress changes.
useEffect(() => {
if (canvas.current && image.current) drawStage(canvas.current, image.current, progress);
}, [progress]);
async function choose(next: File | undefined) {
if (!next) return;
const problem = await checkImage(next);
setMessage(problem);
if (problem) return;
setPreview(next);
setProgress(0);
try {
await upload(next, setProgress);
setProgress(1);
} catch {
setMessage("Upload failed, choose the image to try again");
}
}
return (
<div className="w-full max-w-md">
<label className="block cursor-pointer rounded-2xl border border-dashed border-zinc-300 p-4 text-center text-sm has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-blue-500 dark:border-zinc-700">
{file ? (
<canvas ref={canvas} className="mx-auto h-auto max-w-full rounded-xl" aria-label={`Preview of ${file.name}`} />
) : (
<span>Choose an image</span>
)}
<input
type="file"
accept="image/*"
className="sr-only"
onChange={(event) => {
void choose(event.target.files?.[0]);
event.target.value = "";
}}
/>
</label>
<p className="mt-2 text-xs text-zinc-500" aria-live="polite">
{message ?? (file ? `${Math.round(progress * 100)}%` : "PNG, JPG or WebP, up to 10 MB")}
</p>
</div>
);
}
Two details matter here. The canvas is only mounted once a file exists, so the first effect waits for url before touching it. And the canvas is capped at 640 pixels wide, which keeps the redraws cheap for large photos while still looking sharp on most layouts.
Drag and drop, replacing and removing
Add the drop handling from the file upload guide, with event.dataTransfer.files[0] passed to choose. For replacing, choosing a new image calls setPreview again, and the hook revokes the old object URL. For removing, call setPreview(null), which clears the preview and releases the memory.
Keep one thing in mind with the staged drawing: it is a presentation of real progress, not a substitute for it. If the upload stalls at 40%, the picture should stay at the 40% stage, which is what this does.
Accessibility and motion
- The hidden input inside the label is the real control, so keyboard and screen reader users get the picker without extra code.
- Give the canvas an
aria-labelnaming the file, and keep the percentage as plain text in anaria-liveregion. - If you add movement on top of the stages, such as pixels flying in, honour
prefers-reduced-motionby drawing the final stage directly.
Going further with Nexus UI
The version above shows the picture sharpening in five steps. Pixel Reveal takes the same idea much further. The image arrives as a field of coloured squares flying in from the spot where it was dropped, a ring of rainbow light sweeps out from that point and sharpens the squares behind it from big blocks to small ones to the real picture, and the row underneath shows a thumbnail and a progress bar whose leading edge breaks into flickering pixels. Removing the picture breaks it back into squares that scatter. Pixel Reveal is a Pro component, and it takes the same upload(file, onProgress) function as the code above.
For several files at once, Pearl Drop is the multi-file counterpart, and Upload Dropzone includes an avatar upload with a drag and zoom crop. Install any of them with the shadcn CLI, for example npx shadcn@latest add @nexus-labs/pixel-reveal. The inputs and controls category has the rest of the form components.
Frequently asked questions
How do I preview an image before uploading it in React?
Call URL.createObjectURL(file) when the person picks a file, use the result as the src of an img, and call URL.revokeObjectURL in the effect cleanup. You do not need to read the file with FileReader or send anything to a server first.
Why should I revoke the object URL?
Each object URL keeps its file in memory for as long as the page is open. Revoking it releases that memory. Do it when the image is replaced, removed, or when the component unmounts.
How do I check image dimensions before uploading?
Decode the file with createImageBitmap(file) and read width and height, or load it into an Image and read naturalWidth and naturalHeight. Refuse images below your minimum size and say the size you need.
How do I show a pixelated image that sharpens as it uploads?
Draw the image into a very small canvas, then draw that canvas back to full size with imageSmoothingEnabled set to false so each pixel becomes a block. Increase the small canvas size in steps as progress goes from 0 to 1, and draw the original smoothly at 100%.
How do I limit the size of an uploaded image?
Check file.size in the browser before sending and show the limit in the message. For large photos you can also resize them on a canvas before upload to save bandwidth, but still enforce the limit on the server.
Can I show real upload progress for an image?
Yes. Send the file with XMLHttpRequest and read xhr.upload.onprogress to get bytes sent and the total, then pass a number from 0 to 1 to your component. The fetch API does not report upload progress in every browser.
What image formats should I accept?
accept="image/*" lets the person choose any image type, but the browser can only draw formats it supports. Decode the file with createImageBitmap to confirm it works, and list the formats you really support, such as PNG, JPG and WebP, in the helper text.