Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks: How to write variables in functional components that in class components were initialized in the constructor

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.

like image 505
tinymarsracing Avatar asked May 31 '19 09:05

tinymarsracing


1 Answers

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} />
}
like image 163
Shubham Khatri Avatar answered Sep 22 '22 09:09

Shubham Khatri