Mark As Completed Discussion

Custom Hooks

In React, custom hooks are a way to reuse stateful logic between components. They allow you to encapsulate logic into a reusable function that can be easily shared and composed.

A custom hook is just a JavaScript function that uses one or more built-in hooks, or other custom hooks, and returns stateful values and functions. It follows the naming convention of starting with the word use (e.g. useFetch, useLocalStorage).

Custom hooks enable you to abstract away complex logic and share it across different components in your application. They can be used to handle common tasks like API calls, form handling, state management, and more.

Here's an example of a custom hook that fetches data from an API:

JAVASCRIPT
1// Custom Hook for fetching data
2function useFetch(url) {
3  const [data, setData] = useState(null);
4  const [loading, setLoading] = useState(true);
5  const [error, setError] = useState(null);
6
7  useEffect(() => {
8    const fetchData = async () => {
9      try {
10        const response = await fetch(url);
11        const result = await response.json();
12        setData(result);
13        setLoading(false);
14      } catch (error) {
15        setError(error);
16        setLoading(false);
17      }
18    };
19
20    fetchData();
21  }, [url]);
22
23  return { data, loading, error };
24}
25
26// Usage
27function ExampleComponent() {
28  const { data, loading, error } = useFetch('https://api.example.com/data');
29
30  if (loading) {
31    return <div>Loading...</div>;
32  }
33
34  if (error) {
35    return <div>Error: {error.message}</div>;
36  }
37
38  return <div>Data: {JSON.stringify(data)}</div>;
39}

In this example, the useFetch custom hook encapsulates the logic for fetching data from an API. It uses the useState and useEffect hooks to manage the state of the data, loading status, and error handling. The custom hook is then used in the ExampleComponent to fetch and display the data. If the data is still loading, it shows a loading message, if there is an error, it displays the error message, otherwise it renders the data.

Custom hooks provide a clean and reusable way to organize and share logic in your React components. They help to keep your components focused on rendering and UI concerns, while the custom hooks handle the underlying logic in a decoupled and reusable manner.

Now try creating your own custom hook for a specific logic you frequently use in your projects!

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment