React Custom hooks are one of the most useful feature in react. In modern react application  custom hooks become crucial for developers to allow reusable logic, clean components, and manage state efficiently across applications. It makes the hook  reusable and optimized so in any component it can be use.

In this guide, you’ll explore everything about how to create custom hooks, including their uses, how to manage state inside custom hooks, and real-world examples.

Table of Contents

  • What are React custom hooks
  • Why use custom hooks
  • How state works in hooks
  • Examples
  • State management in custom hooks
  • Best practices

What are React Custom Hooks?

React custom hooks are JavaScript functions. It can include in-built hooks or other logic. In-built hooks example is below that can be use in the custom hooks :

A custom hook must start with the word use. Hooks call inside of the component functions that means it will call on the top level only.

React custom hooks

Example:

function useCounterHandler() {
const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);

  return { count, increment };

}

 Why Use React Custom Hooks?

Using custom hooks provides:

  • Reusable and shared business logic
  • Cleaner components
  • Better state management
  • Easier testing
  • Optimize components

How React Custom Hooks Work

A custom hook extracts reusable business logic from components. It calls on the top of the component function and return the object that have state or anything you want. It will create separate instance on each component so every state of the hook will remain separate.

Without Custom Hook:

Logic repeated in multiple components.

With Custom Hook:

Business logic shared everywhere.

Example: Custom Hook

import { useState } from 'react';

function useOpenorClose(initialValue) {
  const [isOpen, setIsOpen] = useState(initialValue);
   const toggle = () => {
   setIsOpen(prev => !prev)
};
 return { isOpen};
}

Usage:

function AppComponent() {
const { isOpen} = useToggle(true);
    function toggleHandler() {
     // business logic
      }
return (
    <button onClick={toggleHandler}>
    {isOpen ? 'Open' : 'Closed'}
    </button>
  );
}

Managing State in Custom Hooks

using the custom hook state will be centralized so component will be cleaner and manageable. In custom hook we can defined the state and return the state value from the hook.

Example: API call using custom hook

import { useEffect, useState } from 'react';

function useFetchCall( apiCallFn, InitialValue) {
  const [fetchData, setFetchData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
   setIsLoading(true);
    apiCallFn()
      .then(res => res.json())
      .then(result => {
       setIsLoading(false);
        setFetchData(result);
        setIsLoading(false);
      });
  }, [apiCallFn]);
  return { fetchData, isLoading };
}

Usage:

function AppComponent() {
  function apicallUrl {
     // defind api end point and calling
   }
  const { fetchData, isLoading } = useFetchCall (apicallUrl,[]);

    function toggleHandler() {
      // business logic
      }

return (
   <li  fetchData.map((res)=>{
   <span key={res.key}>{res.name}</span>
})
  </li>
  );
}

Example: useReducer in React Custom Hooks

import { useReducer } from 'react';

function reducerState(state, action) {
  switch(action.type) {
    case 'increment':
      return { …state, count: state.count + 1 };
   case 'decrement’:
      return {…state, count: state.count – 1 };
    default:
      return state;
  }
}
function useCounterReducer() {
  const [state, dispatch] = useReducer(reducerState, { count: 0 });
  return { state, dispatch };
}

Usage:

function AppComponent() {

   function apicallUrl {
   // defind api end point and calling
    }
  const { state, dispatch} = useCounterReducer ();

 function toggleHandler() {
   const [state]  = dispatch(‘inicreament’);
  }
return ( <span>{state.count}</span>)
}

Tool Comparison (React Custom Hooks vs Alternatives)

MethodBest ForComplexityReusability
Custom HooksShared logicMediumHigh
ReduxGlobal stateHighHigh
Context APIApp-wide stateMediumMedium
ZustandLightweight stateEasyHigh

Real Uses of React Custom Hooks

1. Authentication

Manage login state.

2. API Requests

Reuse API fetching logic.

3. Form Validation

Centralize validation logic. Add custom validation in the hook.

4. Dark Mode

Share theme state across components and application.

Best Practices for React Custom Hooks

  • Keep hooks reusable and shareable
  • Use descriptive names so that every developer can know what does the hooks
  • Separate UI from logic
  • Include state management in hooks

Advanced Concept: Shared State Hook

function useLocalStorage(key, initialValue) {
   const [value, setValue] = useState(() => {
    return localStorage.getItem(key) || initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, value);
  }, [key, value]);
  return [value, setValue];
}

Conclusion
React custom hooks make component cleaner, scalable, and easier to maintain. They help developers manage state effectively while keeping components simple and reusable.custom hooks should use when you are calling api request that have the same logic in different components so that component will be clean and reusable .

FAQs

What are React custom hooks?

Reusable functions that use React hooks.

Why use custom hooks?

To reuse logic and simplify components.

Can custom hooks manage state?

Yes, using hooks like useState and useReducer.

Are custom hooks better than Redux?
For reusable local logic, yes. Redux is better for large global state.

Final Thoughts
Mastering React custom hooks and state management techniques will help you build scalable,optimized  and maintainable React applications efficiently. It is most crucial feature of the react modern application.

Categorized in:

Tagged in:

,