When you have components that can be used by multiple components, we can extract that component into a custom Hook.
Custom Hooks start with "use". Example: useFetch.
A custom hook is a reusable JavaScript function in React that allows us to reuse logic between multiple components.
Suppose you have two components in your project:
- EmployeeSearch.jsx
- ProductSearch.jsx Both components need to fetch data from a backend API.
Without a custom hook, you might write the same useState, useEffect, loading, and error-handling logic in both components.
This creates duplicate code.
Instead, we can create a custom hook called useFetch and reuse it in both components.
The main advantages are:
- Code reusability — write logic once and reuse it.
- Cleaner components — components focus on displaying the UI.
- Easier maintenance — update the logic in one place.
- Separation of concerns — separate data-fetching logic from UI logic.
Top comments (0)