React Hooks tutorials for beginners-12
Welcome to part-12 of the series. You can find part-11 here. We will learn about useRef hook in this part.
The useRef hook makes it possible to access DOM nodes directly within functional components. So, go ahead and create new React project ref-hook by the below command
npx create-react-app red-hook
Now, in App.js include the FocusInput and remove the earlier default code.
In our project we want to do see the classic use of hook, that is to focus the input box on page load. So, go ahead and create a components folder inside src folder. Create a file FocusInput.js inside it.
First, we want to implement the componentDidMount behaviour, as we want to focus on the input element only once and that is after the component has mounted. We will do this using the useEffect hook with empty array.
After that we will include the useRef hook and use the current.focus() to focus on the input box.
Now, go to localhost and the Input is focussed.
We will look into another use of useRef hook now. For that we will first check it in a class based component. So, go ahead and create a file ClassTimer.js inside the components folder. Here, we have implemented a simple timer using componentDidMount(0 and componentWillUnmount().
Now, include it in App.js.
And the timer works perfectly in localhost.
Now, we want to clear this interval timer on a button click. This is very easy to achieve with a button calling clearInterval.
And it will work as expected.
Now, we want to replicate the exact scenario with functional component. We will create a HookTimer.js inside the components folder. Here, we are using what we had learnt earlier with useEffect hook to implement our timer.
Now, also include the HookTimer in App.js file.
Now, the Counter works perfectly for Hook.
Now, we want to replicate the button used to stop the timer. So, we will add similar functionality as class based component.
But, going back to the browser we see we have a problem.
This happens because the variable interval is defined within the useEffect and doesn’t exist outside of it. Now, here useRef will come to our rescue as it can be used to hold any mutable value. The value will persists through re-renders and will also not cause any additional renders, when it’s value changes.
So, we will store our variable in intervalRef and use the intervalRef.current to use it.
And it will work perfectly as expected with the interval been closed on click of the button.
This completes part-12 of the series. You can find part-13 here.
You can find the code for the same in this github repo.