What is hook?
A hook is a special function that gives powers ๐ช to functional components for a lifecycle as well as a state such as useEffect and useState hooks.
The absence of these inefficiencies was one reason why functional components have long been referred to as
dumb
orstateless
components.
What is Custom Hook?
- A Custom hook ๐๏ธโโ๏ธ is a javascript function whose name starts with
use
and that may call other hooks. Custom hooks are a convention that follows from the design of hooks, rather than a react feature.
Rules For Building Own Custom Hooks
Only call hooks at top level
This rule ensures hooks apply in same order each time a component renders, hence React preserves and knows the state of hooks for multiple useSomething() calls.Only call hooks from react functional components or custom hooks
By following this rule you ensures that all stateful logic is visible from source code and hooks are called unconditionaly at top level.Name your custom hooks starting with use
This ensures automatic checks for voilation of rules of hooks, using eslint-plugin-react-hooks.
Reasoninig Behind Building Own Custom Hooks
To keep your code shallow and modularize
It is about making code easier to read and maintainable, and not going miles deep until something X is found. In Hindi shallow means code ko gambhir nahin karna.
To easily trace different stages of your component effects
Use useState with object state having properties {status, hasError, message, data}, to have single source of truth for handling effects outcome and errors. (Do not forget to add UI for errors)To share stateful logic between components
Hooks solve the problem of sharing stateful logic between components without forcing to add more components to the tree.
Note
- Prefer simplicity over optimization
- Try to resist adding optimization or abstraction too early
Refferences
ย