Introduction
Functions enable use of state and other React features in functional components.
- Simpler Code
- Reduce boilerplate code.
- Skip managing the
this keyword and binding methods.
- Reusable Logic
- Extract stateful logic into reusable "custom hooks".
- Organized Side Effects
- Let related logic to be grouped together within a single function, rather than being split across different lifecycle methods (e.g.,
componentDidMount, componentDidUpdate, componentWillUnmount).
- Example: data fetching and setting up subscriptions with their cleanup.
- Improved Performance
- Through mechanisms like memoization (e.g., with
useMemo and useCallback).
- Prevent unnecessary re-renders of components.
Rules of hooks
- Always call hooks at the top level of your component or custom hook.
- Only call hooks from React functional components or custom hooks.
- Custom hooks should always start with
use, like useFetch or useForm.
Common used hooks
useState
- Lets a function component store dynamic data
- Can set initial value