React - How to split logic from a component

Viewed 457

I have the following component:

const App = () => {
    const registerPushNotificationsToken = () => {
       ...
    };

    useEffect(() => {
       registerPushNotificationsToken();
    }, []);

    return <></>
}

How can I move the function and the useEffect to other file? Should I use a hook or a HOC?

1 Answers

Hooks provide an alternative to HOC and since you are already using react-hooks and functional components, its better to implement a custom hook if it is generic enough to be used into multiple components.

You can extract the above logic to a custom hook like

const usePushNotification = () {}
    const registerPushNotificationsToken = () => {
       ...
    };

    useEffect(() => {
       registerPushNotificationsToken();
    }, []);
}
 export default usePushNotification;

Post this, you can use this in any component like

const App = () => {
    usePushNotification();

    return <></>
}
Related