Bird
Raised Fist0
Reactframework~10 mins

Why custom hooks are used in React - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why custom hooks are used
Write logic in component
↓
Notice repeated logic
↓
Extract logic into custom hook
↓
Use custom hook in multiple components
↓
Share stateful logic cleanly
↓
Simplify components and reuse code
This flow shows how repeated logic in components is extracted into a custom hook, which is then reused to share stateful logic cleanly.
Execution Sample
React
import { useState } from 'react';

function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(c => c + 1);
  return { count, increment };
}

function Counter() {
  const { count, increment } = useCounter();
  return <button onClick={increment}>{count}</button>;
}
This code defines a custom hook useCounter to manage count state and increment logic, then uses it inside a Counter component.
Execution Table
StepActionState BeforeState AfterComponent RenderedOutput
1Call useCounter inside CounterNo count statecount=0Counter<button>0</button>
2User clicks buttoncount=0count=1Counter<button>1</button>
3User clicks button againcount=1count=2Counter<button>2</button>
4Another component uses useCounterNo count statecount=0AnotherComponentInitial count 0
5User clicks button in AnotherComponentcount=0count=1AnotherComponentCount 1
6No more clickscount=1count=1No re-renderOutput stable
7ExitN/AN/AN/AUser stops interaction
💡 User stops interacting, no further state changes or renders
Variable Tracker
VariableStartAfter 1After 2After 3Final
count (Counter)undefined0122
count (AnotherComponent)undefinedundefinedundefinedundefined1
Key Moments - 2 Insights
Why do we extract logic into a custom hook instead of copying it into each component?
Extracting into a custom hook lets us reuse the same logic easily and keeps components simpler, as shown in execution_table rows 1 and 4 where different components use the same hook.
Does each component using the custom hook share the same state?
No, each call to the custom hook creates independent state, as seen in variable_tracker where count in Counter and AnotherComponent are separate.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the count value in the Counter component?
A0
B1
C2
DUndefined
💡 Hint
Check the 'State After' column for step 3 in execution_table
At which step does AnotherComponent first have count state initialized?
AStep 2
BStep 4
CStep 5
DStep 1
💡 Hint
Look for when AnotherComponent calls useCounter in execution_table
If we did not use a custom hook and copied logic into each component, what would change in variable_tracker?
Acount variables would still be independent but code would be duplicated
Bcount variables would be shared between components
Ccount variables would not exist
Dcount variables would be global
💡 Hint
Recall that custom hooks help reuse logic but each component keeps its own state as shown in variable_tracker
Concept Snapshot
Custom hooks let you extract and reuse stateful logic across components.
They keep components simple and avoid code duplication.
Each use of a custom hook has its own independent state.
Use them to share behavior, not state.
Syntax: function useMyHook() { const [state, setState] = useState(); ... return {...}; }
Full Transcript
Custom hooks in React are functions that let you reuse stateful logic across multiple components. Instead of copying the same code into each component, you extract it into a custom hook. Each component calling the hook gets its own independent state. This keeps components simpler and your code DRY (Don't Repeat Yourself). For example, a useCounter hook manages count state and increment logic. When used in different components, each has its own count. The execution table shows how state changes on button clicks and how components re-render. Key points are that custom hooks share logic, not state, and help organize code better.

Practice

(1/5)
1. Why do React developers create custom hooks?
easy
A. To reuse stateful logic across multiple components
B. To style components with CSS
C. To replace React components entirely
D. To write HTML inside JavaScript

Solution

  1. Step 1: Understand the purpose of hooks

    Hooks in React let you use state and other React features without writing a class.
  2. Step 2: Identify why custom hooks are made

    Custom hooks let you reuse stateful logic easily across different components, avoiding repetition.
  3. Final Answer:

    To reuse stateful logic across multiple components -> Option A
  4. Quick Check:

    Custom hooks = reuse logic [OK]
Hint: Custom hooks reuse logic, not styles or HTML [OK]
Common Mistakes:
  • Thinking custom hooks are for styling
  • Believing custom hooks replace components
  • Confusing hooks with HTML syntax
2. Which of the following is the correct way to name a custom hook in React?
easy
A. useFetchData
B. fetchDataHook
C. FetchData
D. hookUseFetch

Solution

  1. Step 1: Recall React naming conventions for hooks

    React requires custom hooks to start with the word 'use' to identify them as hooks.
  2. Step 2: Check each option

    Only 'useFetchData' starts with 'use', following React's convention.
  3. Final Answer:

    useFetchData -> Option A
  4. Quick Check:

    Custom hook names start with 'use' [OK]
Hint: Custom hooks always start with 'use' [OK]
Common Mistakes:
  • Not starting the name with 'use'
  • Using camel case without 'use' prefix
  • Confusing component names with hook names
3. What will be the output of this React component using a custom hook?
function useCounter() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    const timer = setInterval(() => setCount(c => c + 1), 1000);
    return () => clearInterval(timer);
  }, []);
  return count;
}

function Counter() {
  const count = useCounter();
  return 
{count}
; }
medium
A. Throws an error because hooks can't be used here
B. Always shows 0 and never changes
C. A number that increases by 1 every second starting from 0
D. Shows a static string 'count'

Solution

  1. Step 1: Analyze the custom hook useCounter

    It initializes count to 0 and sets up a timer to increase count by 1 every second.
  2. Step 2: Understand the component output

    The Counter component uses useCounter and displays the count, which updates every second.
  3. Final Answer:

    A number that increases by 1 every second starting from 0 -> Option C
  4. Quick Check:

    useCounter returns incrementing count [OK]
Hint: Custom hooks can return changing state values [OK]
Common Mistakes:
  • Thinking count stays 0 forever
  • Believing hooks can't be used in functions
  • Assuming output is a string, not a number
4. Identify the error in this custom hook usage:
function useData() {
  const [data, setData] = React.useState(null);
  fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(json => setData(json));
  return data;
}

function App() {
  const data = useData();
  return <div>{JSON.stringify(data)}</div>;
}
medium
A. Custom hooks cannot return data
B. The fetch call should be inside useEffect to avoid infinite loops
C. useState is used incorrectly and should be replaced with useRef
D. The component should not call the custom hook

Solution

  1. Step 1: Check where fetch is called in useData

    fetch is called directly inside the hook body, causing it to run on every render, leading to infinite loops.
  2. Step 2: Correct usage with useEffect

    fetch should be inside a useEffect with an empty dependency array to run only once on mount.
  3. Final Answer:

    The fetch call should be inside useEffect to avoid infinite loops -> Option B
  4. Quick Check:

    Side effects go inside useEffect [OK]
Hint: Put side effects like fetch inside useEffect [OK]
Common Mistakes:
  • Calling fetch directly in hook body
  • Misusing useState instead of useEffect
  • Thinking hooks can't return values
5. You want to share logic for fetching user data and managing loading state across several components. Which approach best uses custom hooks to solve this?
hard
A. Store user data in a global variable outside React
B. Write the fetch logic separately in each component to avoid dependencies
C. Use a class component instead of hooks for shared logic
D. Create a custom hook that fetches user data and returns both data and loading state

Solution

  1. Step 1: Understand the need for reusable logic

    Fetching data and managing loading state is stateful logic that can be reused with a custom hook.
  2. Step 2: Evaluate options for sharing logic

    Creating a custom hook that returns data and loading state allows multiple components to share this logic cleanly.
  3. Final Answer:

    Create a custom hook that fetches user data and returns both data and loading state -> Option D
  4. Quick Check:

    Custom hooks share stateful logic best [OK]
Hint: Custom hooks bundle related state and logic for reuse [OK]
Common Mistakes:
  • Duplicating fetch code in every component
  • Using class components instead of hooks
  • Using global variables that break React's state flow
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard