Working with Custom Hooks

πŸ“˜ React.js πŸ‘ 44 views πŸ“… Nov 05, 2025
⏱ Estimated reading time: 2 min

Custom Hooks allow you to reuse stateful logic across components. They help keep components clean, readable, and maintainable by extracting logic into reusable functions.


What Is a Custom Hook?

  • A JavaScript function

  • Uses one or more React hooks

  • Name must start with use

  • Can return values, functions, or objects

Example:

function useCounter() { const [count, setCount] = useState(0); return { count, setCount }; }

Why Use Custom Hooks?

  • Reuse logic across components

  • Reduce code duplication

  • Separate logic from UI

  • Improve readability and testing


Rules of Custom Hooks

Custom hooks follow the same rules as React hooks:

  • Call hooks at the top level

  • Only call hooks from React functions

  • Name must start with use


Creating a Custom Hook

Example: useCounter

import { useState } from "react"; function useCounter(initialValue = 0) { const [count, setCount] = useState(initialValue); const increment = () => setCount(c => c + 1); const decrement = () => setCount(c => c - 1); return { count, increment, decrement }; } export default useCounter;

Using a Custom Hook

import useCounter from "./useCounter"; function Counter() { const { count, increment, decrement } = useCounter(10); return ( <> <p>{count}</p> <button onClick={increment}>+</button> <button onClick={decrement}>-</button> </> ); }

Custom Hook with Side Effects

Example: useFetch

import { useEffect, useState } from "react"; function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch(url) .then(res => res.json()) .then(data => { setData(data); setLoading(false); }); }, [url]); return { data, loading }; }

Sharing Logic, Not State

Each component using a custom hook gets its own state.

const a = useCounter(); const b = useCounter();

State is not shared unless using Context or Redux.


Custom Hooks vs Utility Functions

Custom HookUtility Function
Uses React hooksPlain JS
Manages stateNo state
React-specificFramework-agnostic

Best Practices

  • Keep hooks focused on one responsibility

  • Return only what’s needed

  • Handle cleanup in useEffect

  • Place custom hooks in a /hooks folder


Common Use Cases

  • API fetching

  • Form handling

  • Authentication logic

  • Window resize / scroll tracking

  • Debouncing and throttling


Key Takeaways

  • Custom hooks extract reusable logic

  • Improve code organization

  • Follow hook rules

  • Share logic, not UI


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes