Skip to content

4 - Browser functionality related hooks

Course: Custom Hooks - chapter 4

Create a hook that returns true or false based on weather the user is currently online

You are given that -

  1. window.navigator.onLine returns true or false based on weather the user is online
  2. You can attach the following event listeners to listen to weather the user is online or not
window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));
Solution
import { useEffect, useState } from 'react'
function useIsOnline() {
const [isOnline, setIsOnline] = useState(window.navigator.onLine);
useEffect(() => {
window.addEventListener('online', () => setIsOnline(true));
window.addEventListener('offline', () => setIsOnline(false));
}, [])
return isOnline;
}
function App() {
const isOnline = useIsOnline(5);
return (
<>
{isOnline ? "You are online yay!" : "You are not online"}
</>
)
}
export default App

Create a hook that returns you the current mouse pointer position.

The final react app that uses it looks like this

video: https://www.youtube.com/watch?v=Jp6fLijh2Kk

You are given that

window.addEventListener('mousemove', handleMouseMove);

will trigger the handleMouseMove function anytime the mouse pointer is moved.

Solution
import { useEffect, useState } from 'react'
const useMousePointer = () => {
const [position, setPosition] = useState({ x: 0, y: 0 });
const handleMouseMove = (e) => {
setPosition({ x: e.clientX, y: e.clientY });
};
useEffect(() => {
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mousemove', handleMouseMove);
};
}, []);
return position;
};
function App() {
const mousePointer = useMousePointer();
return (
<>
Your mouse position is {mousePointer.x} {mousePointer.y}
</>
)
}
export default App