Bird
Raised Fist0
Reactframework~20 mins

Custom hook best practices in React - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Hook Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this custom hook usage?

Consider this React custom hook that tracks window width. What will the component display after resizing the window to 800 pixels wide?

React
import React, { useState, useEffect } from 'react';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

export default function WidthDisplay() {
  const width = useWindowWidth();
  return <div>Window width is {width}</div>;
}
AWindow width is initial window width before resize
BWindow width is 800
CWindow width is undefined
DComponent crashes with error
Attempts:
2 left
💡 Hint

Think about how the hook updates state on window resize events.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a custom hook that fetches data?

Which of the following custom hook definitions is syntactically correct and follows React hook naming conventions?

Afunction UseFetchData(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url).then(res => res.json()).then(setData); }, [url]); return data; }
Bfunction fetchDataHook(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url).then(res => res.json()).then(setData); }, [url]); return data; }
Cfunction useFetchData(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url).then(res => res.json()).then(setData); }, [url]); return data; }
Dfunction usefetchdata(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url).then(res => res.json()).then(setData); }, [url]); return data; }
Attempts:
2 left
💡 Hint

Custom hooks must start with 'use' and use camelCase.

🔧 Debug
advanced
2:00remaining
Why does this custom hook cause an infinite loop?

Examine this custom hook. Why does the component using it keep re-rendering infinitely?

React
import { useState, useEffect } from 'react';

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

  useEffect(() => {
    setCount(count + 1);
  }, [count]);

  return count;
}
ABecause setCount inside useEffect updates count, triggering useEffect again endlessly
BBecause useState is called inside useEffect causing re-renders
CBecause useEffect has no dependency array causing infinite calls
DBecause count is never updated, so useEffect never stops
Attempts:
2 left
💡 Hint

Think about what happens when state changes inside useEffect with that dependency.

🧠 Conceptual
advanced
2:00remaining
What is a key best practice when creating custom hooks?

Which of the following is a best practice when writing custom React hooks?

ACustom hooks should start with 'use' and can encapsulate stateful logic and side effects
BCustom hooks should only call other hooks and never contain side effects
CCustom hooks must always return JSX elements to be reusable
DCustom hooks should be class components to manage lifecycle methods
Attempts:
2 left
💡 Hint

Think about what custom hooks are designed to do in React.

❓ state_output
expert
3:00remaining
What is the final value of count after this custom hook runs?

Given this custom hook and component, what is the final value of count displayed?

React
import React, { useState, useEffect } from 'react';

function useDelayedIncrement(initial) {
  const [count, setCount] = useState(initial);

  useEffect(() => {
    const id = setTimeout(() => {
      setCount(c => c + 1);
    }, 1000);
    return () => clearTimeout(id);
  }, [count]);

  return count;
}

export default function Counter() {
  const count = useDelayedIncrement(0);
  return <div>{count}</div>;
}
AThe component crashes with a memory leak error
BThe count increases by 1 only once after 1 second
CThe count stays at 0 forever
DThe count increases by 1 every second indefinitely
Attempts:
2 left
💡 Hint

Consider how the effect depends on count and triggers a timeout each time.

Practice

(1/5)
1. Which of the following is a best practice when naming a custom React hook?
easy
A. Start the hook name with use to follow React conventions
B. Name the hook with a capital letter but no prefix
C. Use any name as long as it describes the functionality
D. Prefix the hook name with hook instead of use

Solution

  1. Step 1: Understand React hook naming conventions

    React requires custom hooks to start with use so React can identify them as hooks.
  2. Step 2: Evaluate the options

    Only Start the hook name with use to follow React conventions correctly follows this convention by starting the name with use.
  3. Final Answer:

    Start the hook name with use to follow React conventions -> Option A
  4. Quick Check:

    Hook names start with 'use' = B [OK]
Hint: Always start custom hook names with 'use' [OK]
Common Mistakes:
  • Naming hooks without 'use' prefix
  • Using 'hook' prefix instead of 'use'
  • Starting hook names with lowercase letters without 'use'
2. Which of the following is the correct syntax to define a custom hook that returns a count state and an increment function?
easy
A. function useCount() { const [count, setCount] = useState(0); return { count increment: () => setCount(count + 1) }; }
B. function countHook() { const [count, setCount] = useState(0); return [count, () => setCount(count + 1)]; }
C. function useCount() { const [count, setCount] = useState(0); return [count, () => setCount(count + 1)]; }
D. function useCount() { const count = 0; function increment() { count += 1; } return { count, increment }; }

Solution

  1. Step 1: Check the hook naming and return type

    The hook must start with use and return state and updater properly. function useCount() { const [count, setCount] = useState(0); return [count, () => setCount(count + 1)]; } uses useCount and returns an array with count and increment function.
  2. Step 2: Verify state management correctness

    function useCount() { const [count, setCount] = useState(0); return [count, () => setCount(count + 1)]; } uses useState correctly and returns a function that updates state with setCount(count + 1). This is the correct pattern.
  3. Final Answer:

    function useCount() { const [count, setCount] = useState(0); return [count, () => setCount(count + 1)]; } -> Option C
  4. Quick Check:

    Custom hook syntax with useState and return array = C [OK]
Hint: Custom hooks return state and updater, named starting with 'use' [OK]
Common Mistakes:
  • Not starting function name with 'use'
  • Returning object instead of array without reason
  • Not using useState for state management
  • Mutating state directly instead of using setter
3. Given this custom hook code:
function useToggle(initial) {
  const [on, setOn] = useState(initial);
  const toggle = () => setOn(prev => !prev);
  return [on, toggle];
}

function Component() {
  const [isOn, toggle] = useToggle(false);
  toggle();
  return 
{isOn ? 'ON' : 'OFF'}
; }

What will the component render after calling toggle() once?
medium
A.
ON
B.
false
C.
OFF
D. Error because toggle is called outside an event

Solution

  1. Step 1: Analyze where toggle is called

    toggle() is called directly in the component body, which executes during every render phase.
  2. Step 2: Understand React render rules

    State updates during render trigger re-renders. Since toggle() is unconditional, it flips state every render, causing an infinite loop. React prohibits this and produces errors/warnings (e.g., "Cannot update a component while rendering a different component" or too many re-renders).
  3. Final Answer:

    Error because toggle is called outside an event -> Option D
  4. Quick Check:

    State updaters only in events/effects, not render body [OK]
Hint: Never call state updaters during render; use events or useEffect [OK]
Common Mistakes:
  • Assuming async update shows initial state without considering re-render loop
  • Expecting 'ON' due to toggle flip
  • Confusing boolean with string output
  • Thinking render body calls are safe without infinite loop
4. What is wrong with this custom hook code?
function useCounter() {
  let count = 0;
  const increment = () => { count += 1; };
  return { count, increment };
}
medium
A. It does not use React state, so count won't trigger re-renders
B. The hook name should not start with 'use'
C. The increment function should not modify count
D. It should return an array, not an object

Solution

  1. Step 1: Check state management in the hook

    The hook uses a local variable count that resets to 0 on every call. It does not use useState, so React won't track changes or re-render.
  2. Step 2: Understand React state importance

    Without useState, updating count does not cause component updates, making the hook ineffective.
  3. Final Answer:

    It does not use React state, so count won't trigger re-renders -> Option A
  4. Quick Check:

    Local variable won't update UI without useState [OK]
Hint: Always use useState for reactive state in hooks [OK]
Common Mistakes:
  • Using local variables instead of useState
  • Expecting UI to update without state
  • Returning object instead of array (not always wrong)
  • Misnaming hook without 'use' prefix
5. You want to create a custom hook useFetch that fetches data from a URL and returns loading state, data, and error. Which approach follows best practices?
hard
A. Fetch data directly in the hook body without useEffect, return data and error only
B. Use useEffect inside the hook to fetch data on mount, use useState for loading, data, and error, and return them as an object
C. Use useMemo to fetch data and return loading and data states
D. Fetch data outside the hook and pass it as a parameter to the hook

Solution

  1. Step 1: Understand data fetching in hooks

    Fetching data should happen inside useEffect to avoid running on every render. State variables track loading, data, and error.
  2. Step 2: Evaluate options for best practice

    Use useEffect inside the hook to fetch data on mount, use useState for loading, data, and error, and return them as an object correctly uses useEffect and useState to manage asynchronous fetch and returns all relevant states as an object for clarity.
  3. Final Answer:

    Use useEffect inside the hook to fetch data on mount, use useState for loading, data, and error, and return them as an object -> Option B
  4. Quick Check:

    Fetch in useEffect with state management = A [OK]
Hint: Fetch inside useEffect, manage state with useState [OK]
Common Mistakes:
  • Fetching data directly in hook body causing infinite loops
  • Not managing loading or error states
  • Using useMemo for side effects
  • Passing fetched data as parameter instead of fetching inside hook
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