In this video, we will be building a custom hook step by step in React JS, as we create a useCountdown hook using setInterval, useEffect, and useRef.
First, we'll have a look at the different timer functions in Javascript and how they work.
Then we'll see what happens when we try to apply the same logic to a React Functional Component (I'll give you a hint: it doesn't end well :D)
We'll look at how useEffect solves our problem by allowing us to start side effects when the component is loaded... but our code still doesn't work yet.
The reason for this is the way closures work, this is where useRef comes to the rescue by providing a reference to the current value of the state from within the initial closure environment.
Once the logic of our code works we'll be refactoring it to build a custom countdown hook that we can reuse in our Math Quiz :)
00:00 - Intro
01:09 - Javascript timer functions
02:42 - A naïve implementation (Level 0) - how state triggers re-renders
04:17 - useEffect to the rescue (Level 1) to only trigger the function once
05:05 - the useEffect cleanup function
05:12 - the problem with closures and useEffect
06:42 - useRef to the rescue !
07:50 - Refactoring our code into a custom hook