I'm trying to wrap my head around custom hooks. I understand normal hooks which is just fine, but my question is, when writing a custom hook, what is the difference between that and a normal function? I mean why not call it a normal function instead of calling it something like use*
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. (We don't recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you'd like.)
Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.
Why and When To Use Custom Hooks. The main reason to write a custom hook is for code reusability. For example, instead of writing the same code across multiple components that use the same common stateful logic (say a “setState” or localStorage logic), you can put that code inside a custom hook and reuse it.
Don't call Hooks from regular JavaScript functions. By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
React Hooks (custom or non-custom) should start with the use
prefix. As well as, as per the React Documentation:
1) Hooks should be called from the React code only not from the Regular JS functions. Hence, Hooks' scope is limited to the React code world and has more power to do a lot with React code. Rather than JS, regular functions could be used across application but as react code guidelines keep the code more aligned to react syntax.
2) In the class-based components, the Hooks won't work but regular functions will.
3) In the regular JS functions, you can't access useState
, useEffect
, useContext
etc. but in react custom hooks I can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With