📖 Scenario: You are building a React app that needs to reuse some logic for fetching data from an API. Instead of repeating the same code in multiple components, you want to create a custom hook to keep your code clean and easy to maintain.
🎯 Goal: Build a simple custom hook called useFetchData that fetches data from a URL and returns the data and loading state. Then use this hook in a component to display the fetched data.
📋 What You'll Learn
Create a custom hook named useFetchData that accepts a url parameter.
Inside the hook, use useState to store data and loading states.
Use useEffect to fetch data from the given url when the hook runs.
Return data and loading from the hook.
Create a functional component named DataDisplay that uses useFetchData to fetch and show data.
Show a loading message while data is being fetched.
Display the fetched data once loading is complete.
💡 Why This Matters
🌍 Real World
Custom hooks are used in real React apps to share logic like data fetching, form handling, or animations across many components without repeating code.
💼 Career
Knowing how to write and use custom hooks is important for React developers to build maintainable and scalable applications efficiently.
Progress0 / 4 steps
1
Set up state variables inside the custom hook
Create a custom hook called useFetchData that takes a url parameter. Inside it, use useState to create two state variables: data initialized to null and loading initialized to true.
React
Hint
Remember to import useState and useEffect from React. Start by creating the function and the two state variables.
2
Add useEffect to fetch data from the URL
Inside the useFetchData hook, add a useEffect that runs when the url changes. Inside it, fetch data from the url, convert the response to JSON, then update data with the result and set loading to false.
React
Hint
Use useEffect with url as a dependency. Use fetch to get data, then update states inside the promise chain.
3
Return data and loading from the custom hook
Complete the useFetchData hook by returning an object with data and loading properties.
React
Hint
Return an object with the two state variables so components can use them.
4
Use the custom hook in a component to display data
Create a functional component called DataDisplay. Inside it, call useFetchData with the URL 'https://jsonplaceholder.typicode.com/todos/1'. If loading is true, return a <p> with text Loading.... Otherwise, display the JSON stringified data inside a <pre> tag.
React
Hint
Use the custom hook inside the component. Show loading text while loading is true, then show the data formatted as JSON.
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
Step 1: Understand the purpose of hooks
Hooks in React let you use state and other React features without writing a class.
Step 2: Identify why custom hooks are made
Custom hooks let you reuse stateful logic easily across different components, avoiding repetition.
Final Answer:
To reuse stateful logic across multiple components -> Option A
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
Step 1: Recall React naming conventions for hooks
React requires custom hooks to start with the word 'use' to identify them as hooks.
Step 2: Check each option
Only 'useFetchData' starts with 'use', following React's convention.
Final Answer:
useFetchData -> Option A
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?
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
Step 1: Analyze the custom hook useCounter
It initializes count to 0 and sets up a timer to increase count by 1 every second.
Step 2: Understand the component output
The Counter component uses useCounter and displays the count, which updates every second.
Final Answer:
A number that increases by 1 every second starting from 0 -> Option C
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
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.
Step 2: Correct usage with useEffect
fetch should be inside a useEffect with an empty dependency array to run only once on mount.
Final Answer:
The fetch call should be inside useEffect to avoid infinite loops -> Option B
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
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.
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.
Final Answer:
Create a custom hook that fetches user data and returns both data and loading state -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.