I'm using uppy with React and they normally initialize uppy as a global variable. In React, they allow to do this instead:
class MyComponent extends React.Component {
constructor (props) {
super(props)
this.uppy = Uppy()
.use(Transloadit, {})
}
componentWillUnmount () {
this.uppy.close()
}
render () {
return <StatusBar uppy={this.uppy} />
}
}
How do I write this in a functional component with hooks? The naive approach would be the following (didn't expect it to work after reading this issue):
const MyComponent = () => {
const uppy = Uppy()
.use(Transloadit, {})
useEffect(() => {
return () => uppy.close()
})
return <StatusBar uppy={uppy} />
}
PS: It needs to be done inside of the functional component because I'm using some props in an uppy.use
method.
Variables in functional components can be initialized using useRef
hook (read more here). Also since you only want to run the cleanup function on unmounting and not on every re-render, you should pass an empty []
as the second argument to useEffect
const MyComponent = () => {
const uppy = useRef(Uppy()
.use(Transloadit, {}))
useEffect(() => {
return () => uppy.current.close()
}, [])
return <StatusBar uppy={uppy.current} />
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With