State Management
Learn how State Management works in UploadShad to integrate more smoothly for custom integrations
Overview
Uploaded files and their respective states are stored within the FilesContext which is consumed by the File-Input (The Dropzone) and the Files-Preview (Image previewer and DnD) components.
The FilesContext and useFilesContext hook allow consumers to access images in state, and handler methods to change the state - allowing me to apply separation of concerns while developing.
Learn more about useContext in Nextjs and React.
UploadContext Responsibilities
- Stores the Uploaded Files, and their order
- Provide functions for manipulating state (handleDelete, handleInput, handleDragEnd)
- Prevent unnecessary re-renders in children components when users interact on the page
Memoization
It should be noted that, almost, every client side method in UploadShad and FilesContext uses the useCallback hook to cache functions between re-renders.
This "small" implementation, improved UploadShad's performance by 90% 🤯
Accessing the provided States
UploadedContext will always invoke the Callback function prop passed into the UploadShad handleChange, and provide the urls of uploaded files, and their order.
FilesContext Props
Type
folderId?: string; defaultValues?: string[]; children: React.ReactNode; onChange?: (files: string[]) => void; metadata?: Record<string, string> | undefined;
This is allows for updating the Form state (or any state) with the new values.
If you need to extend UploadShad's features to match your use case, simply create a new component and use the useFilesContext hook to access UploadShad's state data.
FilesContext Handlers
Type
files: string[]; handleDelete: (deletedFile: string) => Promise<boolean>; handleInput: (files: File[]) => Promise<void>; handleReOrder: (source: number, destination: number) => void;
These methods provide the functionality to manipulating state, and execute commands to S3 via the api endpoint "/api/uploadshad".
AWS S3 configuration
It should be noted that any accepted files (files that have been uploaded via the PreSign url), will persist in your storage bucket if the user A. Doesn't submit the form or delete the uploaded file, or B. The user refreshes the page.
Obviously, this can lead to issues depending our use case, and its why I recommend adding metadata values to your images to track temporary files, and submitted files (urls are saved in a database). This will allow you to create/use tools to automatically remove temporary files after a certain period of time.
To implement this, use the metadata prop provided by UploadShad to set any uploaded files as temporary ones. Then ensure before/after saving the urls, that you execute the appropriate command to update the file's (object) metadata to represent a "accepted" state in S3 Storage.