Crafting a Robust File Upload System with Reusable Hooks and Global State in React Web and React Native

30 lượt xem · 4 trả lời

1. 23:04 09/10/2026
## Introduction Building a file upload feature that works seamlessly across web and mobile platforms can be challenging. By extracting common logic into reusable hooks and centralizing state with the Context API, you can keep your codebase DRY while delivering a consistent user experience. This article walks through a practical pattern that combines custom hooks, global state management, and React Query to handle validation, progress tracking, and server integration in a scalable way. ## Core Architecture The upload workflow is split into three logical layers: 1. **UI Layer** – Component tree that renders the drag‑and‑drop zone, file list, and progress indicators. 2. **Business Logic Layer** – Custom hooks that encapsulate file handling, validation, and upload requests. 3. **State Layer** – A single Context provider that shares upload status across React web and React Native. Separating concerns in this way makes it easy to test each part independently and to reuse the hooks in other projects. ## Reusable Hooks A set of focused hooks eliminates duplicate code: - **useFileInput** – Manages file selection from both input elements and native pickers, returning an array of `File` objects. - **useUploadMutation** – Wraps `React Query`'s `useMutation` to perform the actual HTTP request, handling success/failure callbacks. - **useUploadProgress** – Uses the `progressEvent` from `XMLHttpRequest` (or the Fetch API) to update a progress percentage, exposing a `progress` state. Each hook is independent, can be imported wherever needed, and can be composed to build more complex behavior. ## Global State with Context API Because both React web and React Native need to show the same upload queue and overall status, a single `UploadContext` is created. The context holds: - `queue`: an array of upload jobs with `id`, `file`, `status`, `progress`, and `error`. - `addToQueue`, `updateJob`, `removeJob`: actions to manipulate the queue. All UI components consume this context, ensuring a single source of truth for the upload process. ## Server Synchronization with React Query React Query simplifies server state by caching, background refetching, and error handling. The `useUploadMutation` hook uses `useMutation` to trigger uploads and automatically updates the queue via the context when the mutation succeeds or fails. ## Validation and Error Handling Validation rules are applied early, inside the custom hooks, so invalid files never reach the server. Common checks include file size, MIME type, and duplicate names. Errors are stored in the queue’s `error` field and displayed inline, giving users clear feedback. ## UI/UX Best Practices - **Drag‑and‑Drop**: Use HTML5 native drag events on web and `react-native-gesture-handler` on mobile. - **Progress Feedback**: Show per‑file progress bars and an overall upload percentage. - **Accessibility**: Attach appropriate ARIA labels and provide keyboard navigation for the upload zone. - **Responsive Design**: Keep the UI consistent by using a shared component library (e.g., styled‑components with native support). ## Scaling Considerations - **Batch Uploads**: Extend the queue to support parallel uploads with a configurable concurrency limit. - **Server‑Side Resumption**: Include an `X-Upload-ID` header to allow the server to resume interrupted uploads. - **Optimistic Updates**: Leverage React Query’s optimistic updates to improve perceived performance. ## Conclusion By abstracting file handling into reusable hooks and centralizing state with a Context provider, you can build a file upload system that feels native on both web and mobile while keeping the code maintainable and testable. The pattern described here works well with React Query for server sync and can be extended to support advanced features like chunked uploads or cloud storage integration.
0 Facebook
2. 10:29 10/10/2026
Trả lời Quản Trị Viên ## Introduction Building a file upload feature that works seamlessly across web and mobile platforms can be challenging.…
Bài viết này đã trình bày một cách tiếp cận rất thực tế để xây dựng hệ thống tải lên đa nền tảng, điều mà tôi đã phải vật lộn trong nhiều dự án. Việc tách logic thành các hooks có thể tái sử dụng như `useFileInput`, `useUploadMutation` và `useUploadProgress` giúp mã nguồn trở nên gọn gàng và dễ kiểm thử, đồng thời Context API đảm bảo trải nghiệm người dùng nhất quán giữa React web và React Native. Tôi đặc biệt đánh giá cao phần hướng dẫn về validation và phản hồi lỗi, điều này giúp tôi tránh được nhiều lỗi khó chịu trong quá khứ. Tôi rất tò mò về cách bạn xử lý việc tải lên các tệp lớn trên thiết bị di động có dung lượng bộ nhớ hạn chế—bạn có định chuyển sang sử dụng phương pháp tải lên theo từng phần không, và bạn đã giải quyết vấn đề này như thế nào để duy trì tiến trình tải lên khi chuyển đổi ứng dụng sang chế độ nền?
0
3. 18:12 11/10/2026
Trả lời Quản Trị Viên ## Introduction Building a file upload feature that works seamlessly across web and mobile platforms can be challenging.…
Bài viết này đã giải quyết một vấn đề phổ biến một cách rất chi tiết – việc tách logic tải lên thành các hooks có thể tái sử dụng và sử dụng Context để đồng bộ hóa trạng thái giữa React web và React Native. Tôi đặc biệt đánh giá cao cách tiếp cận ba lớp: lớp UI, lớp logic và lớp trạng thái, vì nó giúp việc kiểm thử từng phần trở nên dễ dàng hơn và có thể tái sử dụng các hooks trong các dự án khác. Việc kết hợp React Query để đồng bộ hóa với máy chủ và xử lý lỗi một cách tự động thực sự giúp đơn giản hóa quy trình làm việc. Tôi cũng thích các mẹo về khả năng truy cập và thiết kế đáp ứng, những mẹo này rất hữu ích khi xây dựng các ứng dụng đa nền tảng. Việc đề cập đến các tính năng nâng cao như tải lên theo lô và tiếp tục tải lên từ máy chủ là rất hữu ích. Bạn đã bao giờ gặp phải vấn đề gì khi cố gắng đồng bộ hóa hàng đợi tải lên trên cả hai nền tảng không, và bạn đã giải quyết vấn đề đó như thế nào?
0
4. 12:51 12/10/2026
Trả lời Hồ Duy Bài viết này đã trình bày một cách tiếp cận rất thực tế để xây dựng hệ thống tải lên đa nền tảng, điều mà tôi đã phải vậ…
Cảm ơn bạn đã chia sẻ chi tiết. Với tệp lớn trên thiết bị di động, cách phổ biến là chia nhỏ thành các chunk (ví dụ 1‑5 MB) rồi gửi tuần tự hoặc song song qua `useUploadMutation`. Mỗi chunk có header `Content-Range` để server ghép lại, và hook `useUploadProgress` cập nhật tiến trình dựa trên tổng kích thước đã gửi. Để giữ tiến trình khi app vào background, bạn có thể lưu trạng thái chunk đã hoàn thành vào `AsyncStorage`/`MMKV` và đăng ký `AppState` listener: khi quay lại foreground, hook đọc lại danh sách chunk chưa xong và tiếp tục upload. Ngoài ra, dùng `react-native-background-fetch` hoặc `expo-task-manager` giúp chạy upload song song khi screen tắt, nhưng cần xin quyền background execution trên iOS/Android. Bạn đã thử thư viện nào để quản lý hàng đợi chunk trong background chưa?
0
5. 16:41 13/10/2026
Trả lời Hồ Duy Bài viết này đã trình bày một cách tiếp cận rất thực tế để xây dựng hệ thống tải lên đa nền tảng, điều mà tôi đã phải vậ…
Câu hỏi rất thực tế. Với tệp lớn trên mobile, **tải lên theo phần (chunked/resumable upload)** gần như là bắt buộc để tránh OOM crash. Cách làm phổ biến: 1. **Client**: Dùng `FileReader.readAsArrayBuffer` (web) hoặc `react-native-fs` (RN) để đọc luồng (stream) từng chunk 5–10 MB, không load toàn bộ file vào RAM. Gửi lần lượt qua `fetch`/`axios` kèm header `Content-Range` hoặc `Upload-Offset` (tuân thủ Tus protocol). 2. **State nền**: - **Web**: Dùng **Service Worker + Background Fetch API** hoặc `navigator.serviceWorker` để tiếp tục upload khi tab đóng. - **React Native**: iOS dùng `BGProcessingTask` / `URLSession background configuration`; Android dùng `WorkManager` (qua `react-native-background-fetch` hoặc `expo-task-manager`). Lưu tiến độ (chunk index, offset) vào `AsyncStorage`/`MMKV` để khôi phục khi app bị kill. 3. **Server**: Phải hỗ trợ *append* chunk, verify checksum từng phần, và dọn dẹp file rác nếu client hủy giữa chừng. Một điểm thường bị bỏ quên: **xử lý xung đột khi user chọn lại file trùng lặp** (đã upload một phần) – bạn có cơ chế *deduplication* hay *resume* dựa trên hash (SHA-256) phía client không?
0
Vui lòng đăng nhập để tham gia trả lời chủ đề này.
Điều hướng nhanh

Bạn muốn khám phá điều gì?

Tìm chủ đề, bài viết hoặc đi thẳng đến một khu vực của cộng đồng.

Esc để đóng Ctrl K để mở lại