|
@@ -12,52 +12,26 @@ When using Uppy's React components, an Uppy instance must be passed in to the `u
|
|
|
|
|
|
## Functional Components
|
|
|
|
|
|
-With React Hooks, the `useRef` hook can be used to create an instance once and remember it for all rerenders. The `useEffect` hook can close the Uppy instance when the component unmounts.
|
|
|
+Functional components are re-run on every render. This makes it very easy to accidentally recreate a fresh Uppy instance every time, causing state to be reset and resources to be wasted.
|
|
|
+
|
|
|
+The `@uppy/react` package provides a hook `useUppy()` that can manage an Uppy instance's lifetime for you. It will be created when your component is first rendered, and destroyed when your component unmounts.
|
|
|
|
|
|
```js
|
|
|
-function MyComponent () {
|
|
|
- const uppy = useRef(undefined);
|
|
|
- // Make sure we only initialize it the first time:
|
|
|
- if (uppy.current === undefined) {
|
|
|
- uppy.current = new Uppy()
|
|
|
- .use(Transloadit, {})
|
|
|
- }
|
|
|
+const Uppy = require('@uppy/core')
|
|
|
+const Tus = require('@uppy/tus')
|
|
|
+const { DashboardModal, useUppy } = require('@uppy/react')
|
|
|
|
|
|
- React.useEffect(() => {
|
|
|
- // Return a cleanup function:
|
|
|
- return () => uppy.current.close()
|
|
|
- }, [])
|
|
|
+function MyComponent () {
|
|
|
+ const uppy = useUppy(() => {
|
|
|
+ return new Uppy()
|
|
|
+ .use(Tus, { endpoint: 'https://tusd.tusdemo.net/files' })
|
|
|
+ })
|
|
|
|
|
|
return <DashboardModal uppy={uppy} />
|
|
|
}
|
|
|
```
|
|
|
|
|
|
-With `useRef`, the Uppy instance and its functions are stored on the `.current` property.
|
|
|
-`useEffect()` must receive the `[]` dependency array parameter, or the Uppy instance will be destroyed every time the component rerenders.
|
|
|
-To make sure you never forget these requirements, you could wrap it up in a custom hook:
|
|
|
-
|
|
|
-```js
|
|
|
-function useUppy (factory) {
|
|
|
- const uppy = React.useRef(undefined)
|
|
|
- // Make sure we only initialize it the first time:
|
|
|
- if (uppy.current === undefined) {
|
|
|
- uppy.current = factory()
|
|
|
- }
|
|
|
-
|
|
|
- React.useEffect(() => {
|
|
|
- return () => uppy.current.close()
|
|
|
- }, [])
|
|
|
- return uppy.current
|
|
|
-}
|
|
|
-
|
|
|
-// Then use it as:
|
|
|
-const uppy = useUppy(() =>
|
|
|
- new Uppy()
|
|
|
- .use(Tus, {})
|
|
|
-)
|
|
|
-```
|
|
|
-
|
|
|
-(The function wrapper is required here so you don't create an unused Uppy instance on each rerender.)
|
|
|
+Importantly, the `useUppy()` hook takes a _function_ that returns an Uppy instance. This way, the `useUppy()` hook can decide when to create it. Otherwise you would still be creating an unused Uppy instance on every render.
|
|
|
|
|
|
## Class Components
|
|
|
|