1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Custom Hooks
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
03Hrs
37Mins
50Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Custom Hooks

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
03Hrs
37Mins
50Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Custom Hooks

Overview

As you build React applications, you will find yourself writing the exact same state and useEffect logic across multiple components. For example, fetching data, tracking the mouse position, or listening for window resizing.

Because React Hooks are just JavaScript functions, you can extract this repetitive logic into your own Custom Hooks.

A Custom Hook is simply a standard JavaScript function that starts with the word use (e.g., useWindowSize, useFetch). Inside this function, you can call standard React hooks (like useState and useEffect), encapsulate complex logic, and return whatever data or functions the component needs.

Custom hooks are the ultimate form of logic reusability in React. They allow you to share behavior between components, without sharing the visual UI.

Syntax

Creating and Using a Custom Hook
javascript
// 1. Define the Custom Hook (Must start with 'use')
function useToggle(initialValue = false) {
  // Inside the hook, we can use standard React hooks
  const [value, setValue] = useState(initialValue);

  const toggle = () => {
    setValue(prev => !prev);
  };

  // Return whatever the component might need
  return [value, toggle];
}

// 2. Consume the hook in ANY component
function App() {
  // Now, toggling a boolean is a clean, 1-line operation!
  const [isModalOpen, toggleModal] = useToggle(false);
  const [isDarkMode, toggleDarkMode] = useToggle(true);

  return (
    <div>
      <button onClick={toggleDarkMode}>Switch Theme</button>
      <button onClick={toggleModal}>Open Modal</button>
    </div>
  );
}

Common Pitfalls

  • Not starting the name with 'use': If you name your function fetchData instead of useFetchData, React's linter will not recognize it as a hook. It will allow you to call it conditionally, which will break the Rules of Hooks and crash your app. The use prefix is strictly mandatory.
  • Assuming state is shared between instances: If Component A and Component B both call useToggle(), they do NOT share the same boolean value. Custom hooks reuse the logic, not the state. Every time you call a custom hook, it provisions a completely isolated, independent state instance.

Interview Questions

What is the primary purpose of a Custom Hook?

The primary purpose is logic extraction and reusability. It allows you to take complex, repetitive stateful logic (like fetching data, managing local storage, or handling web sockets) out of the component layer and encapsulate it into a reusable, easily testable function.

Does a Custom Hook have a specific required return type?

No. Unlike useState which must return an array, a custom hook is just a JavaScript function. You can return an array, an object, a primitive string, or absolutely nothing at all. Returning an object { data, isLoading, error } is common for hooks with many properties, while arrays [value, toggle] are common for simple tuples.

Real-World Example

useLocalStorage Hook: This is one of the most famous custom hooks in the React ecosystem. By wrapping useState and localStorage together, we abstract away all the messy JSON.parse and try/catch logic, providing product engineers with a flawless, effortless development experience.

example
javascript
function useLocalStorage(key, initialValue) {
  // Initialize state directly from LocalStorage so data persists across refreshes
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  // Create a wrapped setter function that updates State AND LocalStorage simultaneously
  const setValue = (value) => {
    try {
      setStoredValue(value);
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.log(error);
    }
  };

  return [storedValue, setValue];
}

// IN THE COMPONENT
function Settings() {
  // This behaves exactly like useState, but magically survives page reloads!
  const [theme, setTheme] = useLocalStorage('app-theme', 'dark');
}

Check Your Knowledge

Test your understanding of Custom Hooks with these quick questions.

Question 1

Why is it absolutely mandatory that a custom hook's name starts with 'use'?

Question 2

If two different components call `useCounter()`, what happens to the counter state?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Custom Hooks

Overview

As you build React applications, you will find yourself writing the exact same state and useEffect logic across multiple components. For example, fetching data, tracking the mouse position, or listening for window resizing.

Because React Hooks are just JavaScript functions, you can extract this repetitive logic into your own Custom Hooks.

A Custom Hook is simply a standard JavaScript function that starts with the word use (e.g., useWindowSize, useFetch). Inside this function, you can call standard React hooks (like useState and useEffect), encapsulate complex logic, and return whatever data or functions the component needs.

Custom hooks are the ultimate form of logic reusability in React. They allow you to share behavior between components, without sharing the visual UI.

Syntax

Creating and Using a Custom Hook
javascript
// 1. Define the Custom Hook (Must start with 'use')
function useToggle(initialValue = false) {
  // Inside the hook, we can use standard React hooks
  const [value, setValue] = useState(initialValue);

  const toggle = () => {
    setValue(prev => !prev);
  };

  // Return whatever the component might need
  return [value, toggle];
}

// 2. Consume the hook in ANY component
function App() {
  // Now, toggling a boolean is a clean, 1-line operation!
  const [isModalOpen, toggleModal] = useToggle(false);
  const [isDarkMode, toggleDarkMode] = useToggle(true);

  return (
    <div>
      <button onClick={toggleDarkMode}>Switch Theme</button>
      <button onClick={toggleModal}>Open Modal</button>
    </div>
  );
}

Common Pitfalls

  • Not starting the name with 'use': If you name your function fetchData instead of useFetchData, React's linter will not recognize it as a hook. It will allow you to call it conditionally, which will break the Rules of Hooks and crash your app. The use prefix is strictly mandatory.
  • Assuming state is shared between instances: If Component A and Component B both call useToggle(), they do NOT share the same boolean value. Custom hooks reuse the logic, not the state. Every time you call a custom hook, it provisions a completely isolated, independent state instance.

Interview Questions

What is the primary purpose of a Custom Hook?

The primary purpose is logic extraction and reusability. It allows you to take complex, repetitive stateful logic (like fetching data, managing local storage, or handling web sockets) out of the component layer and encapsulate it into a reusable, easily testable function.

Does a Custom Hook have a specific required return type?

No. Unlike useState which must return an array, a custom hook is just a JavaScript function. You can return an array, an object, a primitive string, or absolutely nothing at all. Returning an object { data, isLoading, error } is common for hooks with many properties, while arrays [value, toggle] are common for simple tuples.

Real-World Example

useLocalStorage Hook: This is one of the most famous custom hooks in the React ecosystem. By wrapping useState and localStorage together, we abstract away all the messy JSON.parse and try/catch logic, providing product engineers with a flawless, effortless development experience.

example
javascript
function useLocalStorage(key, initialValue) {
  // Initialize state directly from LocalStorage so data persists across refreshes
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  // Create a wrapped setter function that updates State AND LocalStorage simultaneously
  const setValue = (value) => {
    try {
      setStoredValue(value);
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.log(error);
    }
  };

  return [storedValue, setValue];
}

// IN THE COMPONENT
function Settings() {
  // This behaves exactly like useState, but magically survives page reloads!
  const [theme, setTheme] = useLocalStorage('app-theme', 'dark');
}

Check Your Knowledge

Test your understanding of Custom Hooks with these quick questions.

Question 1

Why is it absolutely mandatory that a custom hook's name starts with 'use'?

Question 2

If two different components call `useCounter()`, what happens to the counter state?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A