Need for hooks
- Enable developer to write stateful and stateless components without switching class and functions based style.
Rules for hooks
- Only call Hooks at the top level
- It is not allowed to call them inside the loops, conditions, nested functions, or
try/catch/finally blocks
- Call them at the top level in the body of a function component
- Call them at the top level in the body of a custom Hook
- Only call Hooks from React functions
- Don’t call Hooks from regular JavaScript functions
- Call Hooks from React function components
- Call Hooks from custom Hooks
Types of Hooks
- https://react.dev/reference/react/hooks
- Basic Hooks:
useState(): manage state
useEffect(): side effects
useContext(): create common data that is to be accessed by the components hierarchy without having to pass the props down to each level
- Additional Hooks:
useReducer(): used when there is a complex state logic
useRef(): create a reference to the DOM element directly within the functional component
useMemo(): recompute memoized value when dependencies are changed.
useCallback(): cache a function definition between re-renders
- Advanced Hooks:
useImperativeHandle(): lets you customize the handle exposed as a ref
useDebugValue(): lets you add a label to a custom Hook in React DevTools
useLayoutEffect(): version of useEffect that fires before the browser repaints the screen
useDeferredValue(): lets you defer updating a part of the UI
useId(): generating unique IDs that can be passed to accessibility attributes
useImperativeHandle(): lets you customize the handle exposed as a ref.
Custom Hooks
functional returning jsx vs functional component