Last active
June 18, 2025 20:21
-
-
Save DiegoSalazar/090ebd8318d74c7c24af9ad49d7c7f6e to your computer and use it in GitHub Desktop.
Examples of when to create custom React hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from 'react'; | |
// Some component that implements, among many features, a clock display: | |
export function HomePage() { | |
const [time, setTime] = useState(new Date().toLocaleTimeString()); | |
const [timerId, setTimerId] = useState<NodeJS.Timeout | null>(null); | |
useEffect(() => { | |
const id = setInterval(() => { | |
setTime(new Date().toLocaleTimeString()); | |
}, 1000); | |
setTimerId(id); | |
return () => { | |
if (timerId) clearInterval(timerId); | |
}; | |
}, []); | |
return ( | |
<div> | |
<h1>Welcome to the Home Page</h1> | |
<p>It is {time}</p> | |
</div> | |
); | |
} | |
// Now some other component needs the same feature, can duplicate the react state/effect... | |
export function AboutPage() { | |
const [time, setTime] = useState(new Date().toLocaleTimeString()); | |
const [timerId, setTimerId] = useState<NodeJS.Timeout | null>(null); | |
useEffect(() => { | |
const id = setInterval(() => { | |
setTime(new Date().toLocaleTimeString()); | |
}, 1000); | |
setTimerId(id); | |
return () => { | |
if (timerId) clearInterval(timerId); | |
}; | |
}, []); | |
return ( | |
<div> | |
<h1>Welcome to the About Page</h1> | |
<p>It is {time}</p> | |
</div> | |
); | |
} | |
// Or abstract the timer state/effect into a custom hook so we can share the logic between components: | |
export function useClockDisplay() { | |
const [time, setTime] = useState(new Date().toLocaleTimeString()); | |
const [timerId, setTimerId] = useState<NodeJS.Timeout | null>(null); | |
useEffect(() => { | |
const id = setInterval(() => { | |
setTime(new Date().toLocaleTimeString()); | |
}, 1000); | |
setTimerId(id); | |
return () => { | |
if (timerId) clearInterval(timerId); | |
}; | |
}, []); | |
return time; | |
} | |
// Now the page components can use the custom hook to get the clock display without duplicating logic: | |
export function HomePageWithHook() { | |
const time = useClockDisplay(); // state and effect are setup here | |
return ( | |
<div> | |
<h1>Welcome to the Home Page</h1> | |
<p>It is {time}</p> | |
</div> | |
); | |
} | |
export function AboutPageWithHook() { | |
const time = useClockDisplay(); | |
return ( | |
<div> | |
<h1>Welcome to the About Page</h1> | |
<p>It is {time}</p> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment