Ankit Jayaprakash
Ankit Jayaprakash

Reputation: 1110

Replace constructor in class component with Functional component

Thanks in Advance.

Am trying to implement React Native push notification on my project. So how do i replace this code in class component with functional component. I use React Hooks and functional components

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};

    this.notif = new NotifService(
      this.onRegister.bind(this),
      this.onNotif.bind(this),
    );
  }
}

Upvotes: 1

Views: 1246

Answers (1)

Steve Hynding
Steve Hynding

Reputation: 1859

I would transform this into a functional component by setting up an empty object state with a useState hook and wrapping the notif value in a useMemo hook with an empty dependency list. I'm not experienced with React Native components so I created empty callbacks with the useCallback hook to supplement the missing class methods you're referencing. If those are related to React Native API, I am assuming there are equivalent hook exports you can reference.

 import React, { useCallback, useMemo, useState } from 'react'
 
 const App = props => {
   const [state, setState] = useState({})
   const onRegister = useCallback(() => {}, [])
   const onNotif = useCallback(() => {}, [])
   
   const notif = useMemo(() => {
     return new NotifService(onRegister, onNotif)
   }, [])

   return (<>render notif.message (if exists): {notif.message}</>)
 }

Upvotes: 1

Related Questions