Home > Net >  Why use Hub.listen inside useEffect - Amplify Auth
Why use Hub.listen inside useEffect - Amplify Auth

Time:09-12

I'm looking through the documentation at https://docs.amplify.aws/lib/auth/social/q/platform/js/#full-samples and can't understand why Hub.listen is being used within use Effect.

    Hub.listen('auth', ({ payload: { event, data } }) => {
      switch (event) {
        case 'signIn':
        case 'cognitoHostedUI':
          getUser().then(userData => setUser(userData));
          break;
      }
    });

If I'm creating an event listener why should I create in useEffect instead of in the main body of the function.

What am I misunderstanding?

CodePudding user response:

figured it out, I was getting confused between functions and classes. the useEffect with an empty array is being used to only create the event listener on initial render and not on subsequent renders.

Leaving the question up in case anyone else gets similarly confused

CodePudding user response:

This has little to do with functions and classes. It is inside the useEffect(() => {/*...*/}, []) (note the empty dependency list) as it acts as the constructor of the component and is therefore only called once.

If Hub.listen is called inside the render function, this will result in growing list of event listeners, because everytime the component rerenders, a new listener is attached.

To keep you free from any memory issues, you would also detach a listener inside the useEffect hook. So for common listeners, would look like the following:


const App = () => {

    useEffect(() => {
        const listener = () => { console.log('foo'); }

        window.addEventListener('resize', listener);
       
        // destruct
        return () => {
            window.removeEventListener('resize', listener)
        }
    }, []);
}

  • Related