2

I have this hook:

import { useEffect, useState } from 'react';
import { auth } from "../firebase/auth-service"

const useFirebaseAuthentication = () => {
   const [authUser, setAuthUser] = useState(null);

   useEffect(() => {
       const unlisten = auth.onAuthStateChanged(
           authUser => {
               authUser
                   ? setAuthUser(authUser)
                   : setAuthUser(null);
           },
       );
       return () => {
           unlisten();
       }
   });

   return authUser
}

export default useFirebaseAuthentication;

That I use like this:

const authUser = useFirebaseAuthentication();

Is there a way I could use this hook useFirebaseAuthentication() in a class-based component?

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
  • if you want know how to share between components, look the following answer https://stackoverflow.com/questions/65785994/how-to-share-data-from-one-react-native-component-to-another-component/65786436#65786436 – S.N.B Jan 22 '21 at 10:54
  • class have states which are equivalent of hooks. you can share a hook value to class based component, but they should have a paent child relationship – S.N.B Jan 22 '21 at 10:56

1 Answers1

2

Class based components directly donot support Hooks.

Read React-FAQ

You can create a Higher Order Component, like this:

import React from 'react';
import { useFirebaseAuthentication} from '../hooks/useFirebaseAuthentication';

export const withFireBaseAuthHookHOC = (Component: any) => {
  return (props: any) => {
    const authUser = useFirebaseAuthentication();

    return <Component authUser ={authUser} {...props} />;
  };
};

Now just wrap your class based component with this HOC.

.

Rohit Khanna
  • 693
  • 5
  • 15