You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+75Lines changed: 75 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -7301,6 +7301,81 @@ Technically it is possible to write nested function components but it is not sug
7301
7301
7302
7302
**[⬆ Back to Top](#table-of-contents)**
7303
7303
7304
+
306. ### What are Custom React Hooks, and How Can You Develop One?
7305
+
7306
+
**Custom Hooks** in React are JavaScript functions that allow you to **extract and reuse component logic** using React’s built-in Hooks like `useState`, `useEffect`, etc.
7307
+
7308
+
They start with the word **"use"** and let you encapsulate logic that multiple components might share—such as fetching data, handling forms, or managing timers—without repeating code.
7309
+
7310
+
Let's explain the custom hook usage with `useFetchData` example. The `useFetchData` custom Hook is a reusable function in React that simplifies the process of fetching data from an API. It encapsulates common logic such as initiating the fetch request, managing loading and error states, and storing the fetched data. By using built-in Hooks like `useState` and `useEffect`, `useFetchData` provides a clean interface that returns the `data`, `loading`, and `error` values, which can be directly used in components.
7311
+
7312
+
```jsx
7313
+
import { useState, useEffect } from'react';
7314
+
7315
+
functionuseFetchData(url) {
7316
+
const [data, setData] =useState(null); // Holds the response
7317
+
const [loading, setLoading] =useState(true); // Loading state
7318
+
const [error, setError] =useState(null); // Error state
7319
+
7320
+
useEffect(() => {
7321
+
let isMounted =true; // Prevent setting state on unmounted component
7322
+
setLoading(true);
7323
+
7324
+
fetch(url)
7325
+
.then((response) => {
7326
+
if (!response.ok) thrownewError('Network response was not ok');
7327
+
returnresponse.json();
7328
+
})
7329
+
.then((json) => {
7330
+
if (isMounted) {
7331
+
setData(json);
7332
+
setLoading(false);
7333
+
}
7334
+
})
7335
+
.catch((err) => {
7336
+
if (isMounted) {
7337
+
setError(err.message);
7338
+
setLoading(false);
7339
+
}
7340
+
});
7341
+
7342
+
return () => {
7343
+
isMounted =false; // Clean-up function to avoid memory leaks
7344
+
};
7345
+
}, [url]);
7346
+
7347
+
return { data, loading, error };
7348
+
}
7349
+
```
7350
+
7351
+
The above custom hook can be used to retrieve users data for `AuthorList`, `ReviewerList` components.
0 commit comments