javascript - Can I use hooks inside a function (not a functional component) - Stack Overflow

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

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 ponents, but what about the case stated above.

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 ponents, but what about the case stated above.

Share Improve this question edited Sep 10, 2021 at 14:04 iunfixit 9944 silver badges15 bronze badges asked Sep 10, 2021 at 11:28 EricEric 852 silver badges6 bronze badges 1
  • 1 No, you can't: reactjs/docs/hooks-rules.html – Ryan Le Commented Sep 10, 2021 at 11:29
Add a ment  | 

1 Answer 1

Reset to default 5

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

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

Docs: https://reactjs/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 :)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745221233a4617258.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信