Bird
Raised Fist0
Reactframework~20 mins

Reusing logic with hooks in React - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
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 component using a custom hook that counts clicks. What will be displayed after clicking the button 3 times?
React
import React, { useState } from 'react';

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

export default function Clicker() {
  const { count, increment } = useClickCounter();
  return (
    <>
      <button onClick={increment}>Click me</button>
      <p>Clicked {count} times</p>
    </>
  );
}
AClicked undefined times
BClicked 3 times
CClicked NaN times
DClicked 0 times
Attempts:
2 left
💡 Hint
Think about how the state updates with each click and how the count is displayed.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a custom hook that returns a boolean toggle?
You want a custom hook named useToggle that returns a boolean state and a function to flip it. Which code is correct?
A
function useToggle() {
  const [value, setValue] = useState(false);
  const toggle = () =&gt; setValue(value =&gt; !value);
  return { value, toggle };
}
B
function useToggle() {
  const [value, setValue] = useState(false);
  const toggle = () =&gt; setValue(v =&gt; !v);
  return [value, toggle];
}
C
function useToggle() {
  const [value, setValue] = useState(false);
  const toggle = () =&gt; setValue(!value);
  return [value, toggle];
}
D
function useToggle() {
  const [value, setValue] = useState(false);
  function toggle() {
    setValue(!value);
  }
  return { value, toggle };
}
Attempts:
2 left
💡 Hint
Remember to use the functional update form to avoid stale state.
🔧 Debug
advanced
2:00remaining
Why does this custom hook cause an infinite loop?
Examine this custom hook and component. Why does it cause an infinite render loop? function useData() { const [data, setData] = useState(null); fetch('https://api.example.com/data') .then(res => res.json()) .then(setData); return data; } function Component() { const data = useData(); return
{data ? data.message : 'Loading...'}
; }
ABecause the component returns null instead of JSX.
BBecause setData is called with a wrong argument type causing an error.
CBecause useState is used incorrectly without initial value.
DBecause fetch is called on every render inside the hook without useEffect, causing continuous state updates.
Attempts:
2 left
💡 Hint
Think about what happens when state updates inside a hook without controlling side effects.
❓ state_output
advanced
2:00remaining
What is the final count displayed after clicking the button twice?
Given this component using a custom hook, what number will show after clicking the button two times? function useCounter() { const [count, setCount] = useState(0); function increment() { setCount(count + 1); setCount(count + 1); } return { count, increment }; } function Counter() { const { count, increment } = useCounter(); return ; }
ACount: 2
BCount: 0
CCount: 1
DCount: 4
Attempts:
2 left
💡 Hint
Remember how React batches state updates and how stale state values affect setState calls.
🧠 Conceptual
expert
2:00remaining
Which statement best explains why custom hooks must start with 'use'?
Why do React custom hooks have to start with the word 'use'?
ABecause React relies on the 'use' prefix to identify hooks and enforce rules of hooks during compilation and runtime.
BBecause it is a naming convention to help developers remember which functions are hooks, but React does not enforce it.
CBecause hooks starting with 'use' automatically get memoized by React for performance.
DBecause only functions starting with 'use' can access React context.
Attempts:
2 left
💡 Hint
Think about how React detects hooks to apply special rules.

Practice

(1/5)
1. What is the main purpose of creating a custom hook in React?
easy
A. To create new HTML elements
B. To reuse stateful logic across multiple components
C. To style components with CSS
D. To replace React components entirely

Solution

  1. Step 1: Understand what hooks do

    Hooks let you use React features like state and effects inside functions.
  2. Step 2: Identify the role of custom hooks

    Custom hooks let you reuse this logic in many components without repeating code.
  3. Final Answer:

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

    Custom hooks = reuse logic [OK]
Hint: Custom hooks start with 'use' and share logic [OK]
Common Mistakes:
  • Thinking hooks create UI elements
  • Confusing hooks with styling tools
  • Believing hooks replace components
2. Which of the following is the correct way to define a custom hook in React?
easy
A. function useCounter() { const [count, setCount] = useState(0); return [count, setCount]; }
B. function counterHook() { const [count, setCount] = useState(0); return [count, setCount]; }
C. function UseCounter() { const [count, setCount] = useState(0); return [count, setCount]; }
D. function counter() { const [count, setCount] = useState(0); return [count, setCount]; }

Solution

  1. Step 1: Recall naming rules for custom hooks

    Custom hooks must start with 'use' to follow React conventions and enable linting.
  2. Step 2: Check function names

    Only function useCounter() { const [count, setCount] = useState(0); return [count, setCount]; } starts with 'use' and uses camelCase correctly.
  3. Final Answer:

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

    Custom hook names start with 'use' [OK]
Hint: Custom hooks always start with 'use' prefix [OK]
Common Mistakes:
  • Not starting function name with 'use'
  • Using uppercase first letter in hook name
  • Naming hooks like regular functions
3. Given this custom hook code, what will be logged when ExampleComponent renders?
function useToggle(initial) {
  const [on, setOn] = React.useState(initial);
  const toggle = () => setOn(!on);
  return [on, toggle];
}

function ExampleComponent() {
  const [isOn, toggle] = useToggle(false);
  React.useEffect(() => {
    console.log(isOn);
  }, [isOn]);
  return Toggle;
}
medium
A. undefined on first render, then false after button click
B. true on first render, then false after button click
C. No output because console.log is inside useEffect
D. false on first render, then true after button click

Solution

  1. Step 1: Analyze initial state in useToggle

    The hook starts with initial = false, so isOn is false initially.
  2. Step 2: Understand useEffect logging

    useEffect logs isOn after render; initially logs false, after toggle logs true.
  3. Final Answer:

    false on first render, then true after button click -> Option D
  4. Quick Check:

    Initial state false, toggles true [OK]
Hint: Initial state logs first, toggle changes it [OK]
Common Mistakes:
  • Assuming initial state is true
  • Thinking console.log won't run inside useEffect
  • Confusing toggle function behavior
4. What is wrong with this custom hook code?
function useCounter() {
  const [count, setCount] = React.useState(0);
  function increment() {
    count = count + 1;
  }
  return { count, increment };
}
medium
A. Directly modifying count variable instead of using setCount
B. Missing React import for useState
C. increment function should return count
D. Custom hook name should not start with 'use'

Solution

  1. Step 1: Check how state is updated

    State variables like count must be updated via setCount, not by direct assignment.
  2. Step 2: Identify the error in increment

    increment tries to assign count = count + 1, which does not update React state.
  3. Final Answer:

    Directly modifying count variable instead of using setCount -> Option A
  4. Quick Check:

    State updates need setCount [OK]
Hint: Always use setState to update state, never assign directly [OK]
Common Mistakes:
  • Trying to assign state variable directly
  • Forgetting to call setCount
  • Confusing variable assignment with state update
5. You want to create a custom hook useFetch that fetches data from a URL and returns loading state, data, and error. Which approach correctly reuses logic and handles updates safely?
function useFetch(url) {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(res => res.json())
      .then(json => {
        setData(json);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, [url]);

  return { data, loading, error };
}
hard
A. This hook will cause infinite loops because setState is inside useEffect
B. This hook should not use useEffect for fetching data
C. This hook correctly reuses fetch logic and updates state on URL change
D. This hook must return an array, not an object

Solution

  1. Step 1: Check useEffect dependency

    useEffect runs when URL changes, so fetch updates correctly.
  2. Step 2: Verify state updates inside fetch

    State updates happen after fetch resolves or errors, no infinite loops occur.
  3. Step 3: Confirm return value format

    Returning an object with data, loading, error is a common pattern and valid.
  4. Final Answer:

    This hook correctly reuses fetch logic and updates state on URL change -> Option C
  5. Quick Check:

    useEffect fetches on URL change, updates state [OK]
Hint: useEffect with URL dependency safely fetches data [OK]
Common Mistakes:
  • Thinking setState inside useEffect causes loops
  • Not using useEffect for side effects
  • Confusing return types of hooks
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