Created
March 23, 2022 15:40
-
-
Save ViliamKopecky/ece7bcdf61eb8b77bf0150a9569616af to your computer and use it in GitHub Desktop.
useSwitchingInterval
This file contains 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
function useSwitchingInterval<Item>(items: readonly Item[], seconds = 2) { | |
const [active, setActive] = useState(0) | |
useEffect(() => { | |
let timeout: null | NodeJS.Timeout = null | |
const next = () => { | |
setActive((a) => a + 1) | |
timeout = setTimeout(next, seconds * 1000) | |
} | |
next() | |
return () => { | |
if (timeout) { | |
clearTimeout(timeout) | |
} | |
} | |
}, [seconds]) | |
return items[active % items.length] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment