27 July 2022

The useRef Hook allows you to persist values between renders. First example would be to use the hook to update values without causing the component to re-render.

Ref instead of state

Using Ref instead of state variables is useful if you don't want component to re-render when you update the value. The value persists between renders and doesn't cause state updates.
Source code viewer
  1. import React, { useRef, useState } from 'react';
  2.  
  3. export default function App() {
  4. const [count, setCount] = useState(0);
  5.  
  6. // Use useRef for state values without causing the component to re-render.
  7. const countWithRef = useRef(1); // { current: 1 }
  8.  
  9. function increaseCount() {
  10. setCount((prevCount) => prevCount + 1);
  11. }
  12.  
  13. function increaseWithRefCount() {
  14. countWithRef.current = countWithRef.current + 1;
  15. }
  16.  
  17. return (
  18. <div>
  19. <p>You clicked state count {count} times</p>
  20. <p>You clicked ref count {countWithRef.current} times, keep in mind this does not cause re-rendering</p>
  21. <button onClick={increaseCount}>
  22. Increase Count
  23. </button>
  24. <button onClick={increaseWithRefCount}>
  25. Increase With Ref Count
  26. </button>
  27. </div>
  28. );
  29. }
Programming Language: ECMAScript

Ref of DOM node

A simple example that shows how to reference a dom node with useRef hook. This is a concept, dont use this in production. A sidenote: This does cause a typescript error, because the reference does not exist before the first render.
Source code viewer
  1. import React, { useRef, useState } from 'react';
  2.  
  3. export default function App() {
  4. const inputRef = useRef<HTMLInputElement>(null);
  5.  
  6. function focusInput() {
  7. inputRef.current.focus();
  8. // Just an example, bypassing state is not recommended use case.
  9. inputRef.current.value = 'focused';
  10. }
  11.  
  12. return (
  13. <div>
  14. <input ref={inputRef} />
  15. <button onClick={focusInput}>
  16. Fill and Focus
  17. </button>
  18. </div>
  19. );
  20. }
Programming Language: ECMAScript