Home > front end >  React Native using hooks functions and components
React Native using hooks functions and components

Time:12-23

I have a React Native project. I am new to React Native and I am trying to determine from the code provided here in my UserInfo.js should this be classified and used as a component, helper function or a hook

// UserInfo.js
import {useEffect} from 'react';
import {Alert, NativeEventEmitter, NativeModules} from 'react-native';

const userInfoEvents = new NativeEventEmitter(
  NativeModules.ReactNativeSwiftBridge,
);

export const UserInfoAlert = () => {
  useEffect(() => {
    const userInfoMenuListener = userInfoEvents.addListener('onMenu', data => {
      if (data.type === 'UserInfo') {
        Alert.alert(data.message);
      }
    });

    return () => {
      userInfoMenuListener.remove();
    };
  }, []);

  return null;
};

export default UserInfoAlert;

// App.js
const App = () => {
    // other stuff here

    // should it be a hook or function

    return(
        <Navigation>
            <Stack.screen component={{/* */}} />

            {/* Should it be a component */}
        </Navigation>
    )
};

export default App

CodePudding user response:

It doesn't return anything, so it's not a component.

It calls a React hook, so it can only be called at the top level of a React component or other hook - so it should be called a custom hook, rather than a (more general) helper function. So its name should probably be useUserInfoAlert in keeping with React conventions for hook names.

  • Related