2

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.

1

1 Answer 1

5

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.