-1

I was curious about if it's possible to call a custom hook as and when required.

Let's say I have a simple custom hook - useLogToConsole() which just logs 'Hello World' to the console. Now I know I can call this hook on top of my component. But I'd like to call this hook again(as many times as I want to) on a button click.

When I do the same, it works just fine but with an error message that 'React Hook "useCustomHook" cannot be called inside a callback.'

I know this isn't a good coding practice, but I was just curious. Let me know your thoughts.

  • If you want to trigger any kind of function when a button is pressed, you should just make a function and set the button's callback to that function. `onClick={callbackFunction}`. There is no benefit in a hook, a hook is just a callback function that runs in response to variables in the dependency array changes. If your button, were to change the state within the component, the hook could be set up to run in response to that change in state by having it in the dependency array. [Docs](https://react.dev/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component) – Harrison Aug 21 '23 at 08:27

0 Answers0