September 2024
Intermediate to advanced
174 pages
3h 44m
English
React offers several hooks, but the two most important are useState (which we’ve seen) and useEffect. The purpose of useEffect is to schedule code to run outside of the render function. For the auto-advance feature, it wouldn’t make sense to set a timer every time the component renders. We only want to set the timer when the component first mounts, when the slide has advanced, and maybe when the autoAdvanceInterval prop changes.
Let’s write a general-purpose hook to set a timeout with useEffect. We’ll call it useTimeout. Here’s an implementation:
| | import { useEffect } from "react"; |
| | |
| | export const useTimeout = ( |
| | delay: number | undefined, |
| | callback: () => void |
| | ) => ... |
Read now
Unlock full access