ReactError Fix2026 Updated

React useRef Not Working— Fixed [2026]

Also covers: ref.current null · forwardRef · callback ref · DOM refs

January 20265 min readReact 18 · Next.js

⚡ Key Rule — Access ref.current After Mount

component.jsx
const inputRef = useRef(null)

// ❌ WRONG — ref not yet attached during render
console.log(inputRef.current)  // null

// ✅ CORRECT — access after mount in useEffect or event handlers
useEffect(() => {
  inputRef.current.focus()     // DOM element available here
}, [])

return <input ref={inputRef} />

Why ref.current Is Null

React sets ref.current to the DOM element after the component mounts and the element is created in the DOM. During the first render (before mount), ref.current is null. Any code that runs during render cannot access the ref.

1

Read ref.current After Mount

null ref — accessed during render
1 min
components/AutoFocusInput.jsx
import { useRef, useEffect } from 'react'

export default function AutoFocusInput() {
  const inputRef = useRef(null)

  // ✅ Access after mount
  useEffect(() => {
    inputRef.current?.focus()
    inputRef.current?.select()
  }, [])

  function handleScroll() {
    // ✅ In event handlers — element exists when handler fires
    inputRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  return <input ref={inputRef} onFocus={handleScroll} />
}
2

Forward Ref to Custom Component

ref on child component returns null
2 min
components/FancyInput.jsx
import { forwardRef } from 'react'

// ✅ forwardRef passes the ref through to the DOM element
const FancyInput = forwardRef(function FancyInput(props, ref) {
  return (
    <div className="relative">
      <input ref={ref} className="border rounded px-3 py-2" {...props} />
    </div>
  )
})

export default FancyInput

// Parent can now use ref
import { useRef, useEffect } from 'react'
import FancyInput from './FancyInput'

function LoginForm() {
  const emailRef = useRef(null)

  useEffect(() => {
    emailRef.current?.focus()  // works!
  }, [])

  return <FancyInput ref={emailRef} type="email" placeholder="Email" />
}
3

useImperativeHandle — Expose Specific Methods

Control what the parent can do with the ref
2 min
components/VideoPlayer.jsx
import { forwardRef, useImperativeHandle, useRef } from 'react'

const VideoPlayer = forwardRef(function VideoPlayer(props, ref) {
  const videoRef = useRef(null)

  // ✅ Expose only specific methods to the parent
  useImperativeHandle(ref, () => ({
    play:  () => videoRef.current.play(),
    pause: () => videoRef.current.pause(),
    seek:  (t) => { videoRef.current.currentTime = t },
    // Parent cannot access the raw DOM element — just these methods
  }))

  return <video ref={videoRef} src={props.src} />
})

// Usage
function Controls() {
  const playerRef = useRef(null)
  return (
    <div>
      <VideoPlayer ref={playerRef} src="/video.mp4" />
      <button onClick={() => playerRef.current.play()}>Play</button>
    </div>
  )
}
4

Callback Ref — Run Code on Mount

Execute logic exactly when element appears
2 min
component.jsx
// Callback ref — fires with element on mount, null on unmount
function MeasuredBox() {
  const [size, setSize] = useState({ width: 0, height: 0 })

  const measuredRef = (node) => {
    if (node !== null) {
      setSize({
        width:  node.getBoundingClientRect().width,
        height: node.getBoundingClientRect().height,
      })
    }
  }

  return (
    <div ref={measuredRef} className="bg-gray-100 p-4">
      Size: {size.width} x {size.height}
    </div>
  )
}
5

Mutable Ref — Store Values Without Re-render

Track values without triggering renders
2 min
components/StopWatch.jsx
import { useState, useRef } from 'react'

export default function StopWatch() {
  const [elapsed,   setElapsed]   = useState(0)
  const intervalRef = useRef(null)   // mutable ref — no re-render on change
  const startTime   = useRef(null)

  function start() {
    startTime.current = Date.now() - elapsed
    intervalRef.current = setInterval(() => {
      setElapsed(Date.now() - startTime.current)
    }, 10)
  }

  function stop() {
    clearInterval(intervalRef.current)
  }

  return (
    <div>
      <p>{(elapsed / 1000).toFixed(2)}s</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </div>
  )
}

Prevention

Frequently Asked Questions

Why is ref.current null in React?+
refs are populated after the component mounts and the DOM element is created. During the initial render (before mount), ref.current is null. Always access ref.current inside useEffect, event handlers, or other callbacks — never directly in the render body.
How do I pass a ref to a custom component?+
Use React.forwardRef: const MyInput = forwardRef((props, ref) => <input ref={ref} {...props} />). Then the parent can pass a ref to it: const inputRef = useRef(null); <MyInput ref={inputRef} />.
Can I put a ref on a function component?+
Not directly — function components do not have instances. You must use forwardRef to forward the ref to a DOM element inside the component. In React 19, refs will be passable as regular props, but for now forwardRef is required.
What is useRef used for in React?+
Two main uses: 1) Accessing DOM elements directly: const divRef = useRef(null); <div ref={divRef}> — then divRef.current is the DOM element. 2) Storing mutable values that should not trigger re-renders: const countRef = useRef(0); countRef.current++.
Difference between useRef and useState for storing values?+
useState triggers a re-render when the value changes. useRef does not. Use useState when the UI needs to update based on the value. Use useRef when you need to store something (interval ID, previous value, DOM node) without causing a re-render.
How do I run code when an element appears in the DOM?+
Use a callback ref: <div ref={(node) => { if (node) { console.log('mounted', node) } else { console.log('unmounted') } }}> The callback fires with the DOM element when it mounts and with null when it unmounts.

Need Expert Help?

We Build Production-Grade React Apps

Softplix builds full-stack React applications. Need help with complex ref patterns or component architecture? We can help.

Talk to an Engineer