DEV Community

Cover image for React Custom Hooks
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

React Custom Hooks

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:

  1. Code reusability — write logic once and reuse it.
  2. Cleaner components — components focus on displaying the UI.
  3. Easier maintenance — update the logic in one place.
  4. Separation of concerns — separate data-fetching logic from UI logic.

Top comments (0)