sajad torkamani

What is useRef useful for?

useRef serves two main purposes:

  1. Store a reference to a DOM node or React element that will persist throughout a component’s life cycle – even between re-renders. In this sense, it’s similar to React.createRef. See this post for more about refs.
  2. Store a reference to a mutable value that will persist throughout the component lifecycle. In this sense, useRef can be used as an alternative instance variables in a class component. For example, you can use useRef to store a reference to the return value of setInterval and then use this value to cancel the timer in the cleanup callback of useEffect.

Example usage

function TextInputWithFocusButton() {
  const inputEl = useRef(null)
  const onButtonClick = () => {
    // `current` points to the mounted text input element

  return (
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>

Other notes

  • Mutating the current property doesn’t cause a re-render. If you must run code when a ref to a DOM node is attached or detached, consider using ref callbacks.


Tagged: React