Custom hook file name: start "use" keyword so react understood that this function is Customer hook. Syntax: useHookName.js
Example for fetch logic :
const useFetch(url) {
const [fetchData, SetFetchData]=useState()
useEffect(()=>{
fetchData()
},[])
const fetchData= async()=>{
// write the fetch logic here
// update the state variable.
}
return fetchData;
}
Checking online or offline hook :
const useOnlineStatus() {
const [onlineStatus, SetOnlineStatus]=useState(true)
useEffect(()=>{
window.eventListener("offline",()=> setOnlineStatus(false))
window.eventListener("online",()=> true
},[])
return onlineStatus;
}
This hook is executed once and attached the event to our web page and the event keeps tracking the online status.
let onlineStatus = useOnlineStatus()
onlineStatus? <Online page> : <offline message page>..