ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Orchestrating Multiple Custom Hooks for Complex State

JSX

Goal -- WPM

Ready
Exercise Algorithm Area
1function useFetch(url) {
2const [data, setData] = React.useState(null);
3const [loading, setLoading] = React.useState(false);
4const [error, setError] = React.useState(null);
5
6const fetchData = React.useCallback(async () => {
7setLoading(true);
8setError(null);
9try {
10const response = await fetch(url);
11if (!response.ok) {
12throw new Error(`HTTP error! status: ${response.status}`);
13}
14const result = await response.json();
15setData(result);
16} catch (err) {
17setError(err);
18} finally {
19setLoading(false);
20}
21}, [url]);
22
23return { data, loading, error, fetchData };
24}
25
26function useDebounce(value, delay) {
27const [debouncedValue, setDebouncedValue] = React.useState(value);
28
29React.useEffect(() => {
30const handler = setTimeout(() => {
31setDebouncedValue(value);
32}, delay);
33
34return () => {
35clearTimeout(handler);
36};
37}, [value, delay]);
38
39return debouncedValue;
40}
41
42function useCombinedFetch(initialUrl, debounceDelay) {
43const [searchTerm, setSearchTerm] = React.useState('');
44const debouncedSearchTerm = useDebounce(searchTerm, debounceDelay);
45const { data, loading, error, fetchData: fetchWithUrl } = useFetch(initialUrl);
46
47React.useEffect(() => {
48if (debouncedSearchTerm) {
49fetchWithUrl(`${initialUrl}?q=${debouncedSearchTerm}`);
50} else {
51// Optionally clear data or fetch default if search term is empty
52// setData(null);
53}
54}, [debouncedSearchTerm, initialUrl, fetchWithUrl]);
55
56const handleSearchChange = (event) => {
57setSearchTerm(event.target.value);
58};
59
60return {
61searchTerm,
62handleSearchChange,
63data,
64loading,
65error,
66};
67}
Algorithm description viewbox

Orchestrating Multiple Custom Hooks for Complex State

Algorithm description:

This scenario focuses on orchestrating multiple custom hooks to manage complex asynchronous operations. It combines a debouncing hook with a data fetching hook to create a search input that only triggers an API call after a user has stopped typing for a specified duration. This pattern is common in applications requiring real-time search suggestions or filtering.

Algorithm explanation:

The `useCombinedFetch` hook orchestrates `useDebounce` and `useFetch`. The `useDebounce` hook delays the update of `debouncedSearchTerm` until the user pauses typing, preventing excessive API calls. The `useFetch` hook handles the actual network request. When `debouncedSearchTerm` changes, a new fetch request is initiated. The overall loading and error states are derived from the `useFetch` hook. Time complexity is dominated by the `fetch` operation, typically O(N) where N is the size of the data returned. Space complexity is O(1) excluding the data stored by the fetch hook itself. Edge cases include network failures, empty search terms, and rapid typing.

Pseudocode:

Define `useCombinedFetch` hook:
Initialize `searchTerm` state.
Use `useDebounce` to get `debouncedSearchTerm` from `searchTerm`.
Use `useFetch` to get `data`, `loading`, `error`, and `fetchData`.
Use `useEffect` to trigger `fetchData` when `debouncedSearchTerm` changes.
Define `handleSearchChange` to update `searchTerm`.
Return `searchTerm`, `handleSearchChange`, `data`, `loading`, `error`.