Using useRef to directly access DOM elements and persist state values
The useRef
Hook allows you to access DOM elements directly in React and is used to persist state values across re-renders. React, as a powerful library for UI, has a lot of novel concepts (virtual DOM design patterns, event handling, attribute manipulation) we can use to access and manipulate DOM elements without the use of traditional DOM methods.
This declarative approach to DOM is one of the reasons React is so popular. However, with useRef
, we can directly access DOM elements and freely manipulate them without consequence. The team at React felt that with useRef
, developers’ present and future cravings for direct DOM access might be met despite the React abstraction on top of the DOM.
There are two core uses of useRef
:
- Accessing DOM elements directly
- Persisting state values that do not trigger the re-rendering of React components when updated
If you are interested in how many times...