ReactJS Program to Custom useFetch Hook with Explanation
ReactJS
Hard
Hooks & Effects
28 views
1 min read
84 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around usefetch, hook, react. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a useFetch hook that returns loading/error/data.
Input Format
No input.
Output Format
Render a React component.
Constraints
Fetch in effect and protect against unmount.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useEffect, useState } from 'react';
function useFetch(url) {
const [state, setState] = useState({ loading: true, error: '', data: null });
useEffect(() => {
let cancelled = false;
async function run() {
setState({ loading: true, error: '', data: null });
try {
const res = await fetch(url);
const json = await res.json();
if (!cancelled) setState({ loading: false, error: '', data: json });
} catch (e) {
if (!cancelled) setState({ loading: false, error: String(e.message || e), data: null });
}
}
run();
return () => { cancelled = true; };
}, [url]);
return state;
}
export default function App() {
const { loading, error, data } = useFetch('https://jsonplaceholder.typicode.com/todos/1');
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode fetch hook</h2>
{loading ? <div>Loading...</div> : null}
{error ? <div style={{ color: '#c1121f' }}>{error}</div> : null}
{data ? <pre style={{ background: '#f6f8fa', padding: 12, borderRadius: 14 }}>{JSON.stringify(data, null, 2)}</pre> : null}
</div>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Create a useFetch hook that returns loading/error/data.
Input / Output
Output
Render a React component.
Constraints
Fetch in effect and protect against unmount.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
import React, { useEffect, useState } from 'react';
function useFetch(url) {
const [state, setState] = useState({ loading: true, error: '', data: null });
useEffect(() => {
let cancelled = false;
async function run() {
setState({ loading: true, error: '', data: null });
try {
const res = await fetch(url);
const json = await res.json();
if (!cancelled) setState({ loading: false, error: '', data: json });
} catch (e) {
if (!cancelled) setState({ loading: false, error: String(e.message || e), data: null });
}
}
run();
return () => { cancelled = true; };
}, [url]);
return state;
}
export default function App() {
const { loading, error, data } = useFetch('https://jsonplaceholder.typicode.com/todos/1');
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode fetch hook</h2>
{loading ? <div>Loading...</div> : null}
{error ? <div style={{ color: '#c1121f' }}>{error}</div> : null}
{data ? <pre style={{ background: '#f6f8fa', padding: 12, borderRadius: 14 }}>{JSON.stringify(data, null, 2)}</pre> : null}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!