Examples of Creating Custom Hooks in React
Example 1: Suppose we have to fetch data from GitHub API and use it in multiple components, instead of fetching data in every component, we will create a custom hook, and separate the logic of fetching the data easily.
- Always add the “use” prefix in name of hook.
- Keep in mind that one hook should perform a single task only, not more than one, as this increases the modularity of the code and makes the code easier to understand and test.
- While testing, test these hooks with different scenarios and testcases to ensure they are working properly.
Javascript
// useGitHubData.js import { useState, useEffect } from 'react' ; const useGitHubData = (username) => { const [userData, setUserData] = useState( null ); const [loading, setLoading] = useState( false ); const [error, setError] = useState( '' ); useEffect(() => { const fetchData = async () => { if (!username) return ; setLoading( true ); try { const response = await fetch(`https: //api.github.com/users/${username}`); if (!response.ok) { throw new Error ( 'User not found or failed to fetch data' ); } const data = await response.json(); setUserData(data); setError( '' ); } catch (error) { setError( 'User not found or failed to fetch data' ); setUserData( null ); } setLoading( false ); }; fetchData(); }, [username]); return { userData, loading, error }; }; export default useGitHubData; |
Javascript
// GithubDataComponent.js import useGitHubData from './useGitHubData' ; const GitHubDataComponent = () => { const { userData, loading, error } = useGitHubData( "Tapesh-1308" ); // Log userData, loading, and error to the console console.log( "UserData:" , userData); console.log( "Loading:" , loading); console.log( "Error:" , error); return <></>; }; export default GitHubDataComponent; |
Output:
Example 2: Let’s see another example to get more clarity, why not build a feature that will tell if the user is online or not? Companies use this same feature to show if the user is online or not.
Javascript
// useOnlineStatus.js import { useState, useEffect } from 'react' ; const useOnlineStatus = () => { const [isOnline, setIsOnline] = useState(navigator.onLine); useEffect(() => { const handleOnline = () => { setIsOnline( true ); }; const handleOffline = () => { setIsOnline( false ); }; window.addEventListener( 'online' , handleOnline); window.addEventListener( 'offline' , handleOffline); return () => { window.removeEventListener( 'online' , handleOnline); window.removeEventListener( 'offline' , handleOffline); }; }, []); return isOnline; }; export default useOnlineStatus; |
Javascript
// OnlineStatusComponent.js import useOnlineStatus from './useOnlineStatus' ; const OnlineStatusComponent = () => { const isOnline = useOnlineStatus(); console.log( "User is online:" , isOnline); return <></>; }; export default OnlineStatusComponent; |
Output:
How to create a Custom Hook in React ?
Custom Hooks are special functions that we create in our application to extract certain functionality and increase reusability. These hooks are basically just regular JavaScript functions that begin with the prefix “use“. If you’re reading this, chances are you’re already familiar with built-in hooks such as useState and useEffect. After going through this article, you’ll gain a better understanding of custom hooks.
Table of Content
- What is a Custom Hook?
- How to Create a Custom Hook?
- Steps to Create Custom Hook in React Application
- Examples of Creating Custom Hooks in React
- Conclusion
Contact Us