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
import React, { useRef, useState } from 'react'; export default function App() { const [count, setCount] = useState(0); // Use useRef for state values without causing the component to re-render. const countWithRef = useRef(1); // { current: 1 } function increaseCount() { setCount((prevCount) => prevCount + 1); } function increaseWithRefCount() { countWithRef.current = countWithRef.current + 1; } return ( <div> <p>You clicked state count {count} times</p> <p>You clicked ref count {countWithRef.current} times, keep in mind this does not cause re-rendering</p> <button onClick={increaseCount}> Increase Count </button> <button onClick={increaseWithRefCount}> Increase With Ref Count </button> </div> ); }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
import React, { useRef, useState } from 'react'; export default function App() { const inputRef = useRef<HTMLInputElement>(null); function focusInput() { inputRef.current.focus(); // Just an example, bypassing state is not recommended use case. inputRef.current.value = 'focused'; } return ( <div> <input ref={inputRef} /> <button onClick={focusInput}> Fill and Focus </button> </div> ); }Programming Language: ECMAScript