Custom Hooks

Subject: React

๐Ÿ“ What Are Custom Hooks?

A Custom Hook is a JavaScript function that starts with use and calls other hooks (like useState, useEffect, etc.).

They let you reuse stateful logic across components โ€” making your code cleaner, modular, and easier to maintain.


๐ŸŽฏ Why Use Custom Hooks?

Problem:

You keep duplicating the same state logic in multiple components.

โœ… Solution:

Extract that logic into a custom, reusable hook and use it wherever needed.


โœ… When to Use a Custom Hook

Use CaseReason to Use a Custom Hook
Repeated use of useEffectAbstract side effects like data fetching
Shared useState logicReuse input/toggle logic
Complex logic (timers etc.)Clean up component code
Working with APIs/storageEncapsulation and reusability

๐Ÿงฑ Custom Hook Rules

  • Must start with use
  • Can call other hooks (useState, useEffect, etc.)
  • Cannot be called inside loops, conditions, or nested functions
  • Must follow normal React Hook Rules

โœ… Basic Custom Hook Example: useCounter

๐Ÿ”ง useCounter.js

๐Ÿงช Usage in Component


โœ… Custom Hook with useEffect: Fetch API

๐Ÿ”ง useFetch.js

๐Ÿงช Usage in Component


๐Ÿง  Benefits of Custom Hooks

BenefitDescription
โ™ป๏ธ ReusabilityUse the same logic in multiple components
๐Ÿงผ Cleaner CodeKeeps component logic short and focused
๐Ÿงช TestabilityHooks are just functions โ€” easy to unit test
๐Ÿ›  ComposabilityCustom hooks can call other custom hooks

๐Ÿ“ฆ More Examples of Custom Hooks

Custom HookDescription
useToggle()Toggle a boolean value
useLocalStorage()Sync state with localStorage
useDebounce()Debounce fast-changing input values
useWindowSize()Track window width & height
usePrevious()Get the previous value of a prop/state

๐Ÿ“Œ Summary Table

ConceptDescription
What is it?A reusable function that uses other React Hooks
NamingMust start with use
Return valuesTypically returns an object with logic or state
Hook rulesSame as normal hooks โ€” no conditional or loop calls
BenefitsCleaner, reusable, composable, testable code

๐Ÿง  Real-Life Analogy

A custom hook is like a power tool ๐Ÿ› ๏ธ โ€” once built, you can plug it in and reuse it in any project to speed up your workflow and reduce manual effort.