最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论