From the course: Build Modern Web Apps with React, Hooks, State Management, and APIs Using Vite or Next.js

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

useRef timer example: Mutable values

useRef timer example: Mutable values

Welcome back, in this video we will see using the useRef hook how we can store the mutable values. We can store a value that does not trigger a re-render when we change it, unlike the useState hook. You will observe that in this example no re-renders will occur and the variable is going to change its value as well. Since they are not a state variable, that's why useRef hook allows us to preserve that value. We are going to do a count example. We'll put up a timer component. We'll declare a useRef for the count variable with an initial value of zero. We'll use a useEffect hook in combination and inside it, we'll set a timer interval. In each one second tick of that timer, we are going to update the current value by 1. And we'll also have a cleanup function which is going to clear out that interval. And we'll observe that in the component tree, we are not going to have any re-renders and the value is also going to be updated. Let's quickly see that in action. I have also put in an…

Contents