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