Divide & Conquer: Custom Hooks
Mission
Separate business logic from the UI by extracting data fetching into a reusable, generic Custom Hook.
Tasks
- 1
Open
hooks/useFetch.jsand move the state (data,loading,error) and theuseEffectinto it. - 2
Make the Hook generic: it receives a
urlparameter. - 3
Return an object
{ data, loading, error }. - 4
Refactor
App.jsto calluseFetchand remove every trace of fetching from the component. - 5
Render the loading state, the error, and the list of products.
import React from 'react'; import { useFetch } from "./hooks/useFetch"; import './styles.css'; export default function App() { // 1. Use your new useFetch hook here // URL: 'https://fakestoreapi.com/products?limit=5' // 2. Extract data, loading and error (you can rename data to products) // Tip: keep only rendering logic here (if loading, if error...) return ( <div className="container"> <h1>FakeStore Products</h1> <div className="grid"> {/* 3. Map your products here */} </div> </div> ); }
Requirements
0/9App.js has no useEffect or fetch (not run yet)
App.js calls useFetch(url) (not run yet)
The hook receives the URL as a parameter (not run yet)
The hook owns data, loading and error (not run yet)
The hook fetches inside useEffect (not run yet)
The hook returns { data, loading, error } (not run yet)
The hook handles failures (try/catch and res.ok) (not run yet)
The effect depends on [url] (not run yet)
No hardcoded URL inside the hook (not run yet)
AI mentor
Reviews only the files you changed, plus the checks you missed.
Run the checks first. They are free and instant.