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 common cases and comparison with useState

useRef common cases and comparison with useState

Welcome back. Let's discuss how useRef is different from useState and based on what criterias they make a difference. We are going to see feature-wise useRef and useState comparison. The first is that it triggers a re-render. The useRef does not, but useState does. The persistence across rendering, it's a yes for both, both preserve the value across re-rendering. The DOM access, yes, the useRef can access the DOM elements, but useState cannot access the DOM elements. Let's discuss the common use cases we can have for userif when we want to avoid re-renders while keeping track of the previous values, when we are interfacing with a third-party library, for example, for rendering animations or animation counters, or if we want to access a DOM element and manipulate its state or its functionality like focusing it or doing a hover effect on it. Lastly, we can store the intervals or timeout IDs. So we want to refresh the screen, maybe call an API to refresh the data after a timer. We can…

Contents