Eric
Eric

Reputation: 85

Can I use hooks inside a function (not a functional component)

Here is where I would like to use my hook so that I can change one state during the run of the app.

export const simpleFunction = () => (state) => {
   // here is the hook 
}

I know react hooks should be used in functional components, but what about the case stated above.

Upvotes: 2

Views: 5621

Answers (1)

Ling Vu
Ling Vu

Reputation: 5181

Yes you can! Those functions are then called custom hooks. But it is required to use those custom hooks inside of a functional component. So technically it is now a function using hooks outside of a react component, but they still need to be bound to a component later.

Building your own Hooks lets you extract component logic into reusable functions.

Docs: https://reactjs.org/docs/hooks-custom.html

Example from the docs

import { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}

Because your descriptions is so short I don't know if this is what you are looking for. Hope I could help :)

Upvotes: 5

Related Questions