admin管理员组文章数量:1415145
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
1 Answer
Reset to default 5Yes 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 :)
本文标签: javascriptCan I use hooks inside a function (not a functional component)Stack Overflow
版权声明:本文标题:javascript - Can I use hooks inside a function (not a functional component) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745221233a2648404.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论