React Interview Reference

Back to home

useRef Hook

The useRef hook creates a mutable reference that persists across renders.

DOM References

useRef is commonly used to access DOM elements directly.

jsx
import { useRef, useEffect } from 'react';

function FocusInput() {
  // Create a ref
  const inputRef = useRef(null);

  // Focus the input on mount
  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return <input ref={inputRef} type="text" />;
}

Storing Mutable Values

useRef can store any mutable value that persists between renders.

jsx
import { useRef, useEffect } from 'react';

function IntervalExample() {
  // Store the interval ID
  const intervalRef = useRef(null);

  useEffect(() => {
    // Set up the interval
    intervalRef.current = setInterval(() => {
      console.log('Interval triggered');
    }, 1000);
    
    // Clean up the interval
    return () => {
      clearInterval(intervalRef.current);
    };
  }, []);

  return <div>Check console for interval logs</div>;
}

Tracking Previous Values

useRef can be used to keep track of previous prop or state values.

jsx
import { useState, useEffect, useRef } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  // Store the previous count value
  const prevCountRef = useRef();

  useEffect(() => {
    // Update the ref after render
    prevCountRef.current = count;
  });

  const prevCount = prevCountRef.current;

  return (
    <div>
      <h1>Now: {count}, before: {prevCount}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Avoiding Re-renders

Unlike state, updating a ref doesn't trigger a re-render.

jsx
import { useRef, useState } from 'react';

function RenderCounter() {
  const [, forceRender] = useState({});
  // This value persists between renders but doesn't cause re-renders
  const renderCount = useRef(0);

  // Increment on each render
  renderCount.current += 1;

  return (
    <div>
      <p>This component has rendered {renderCount.current} times</p>
      <button onClick={() => forceRender({})}>Force render</button>
    </div>
  );
}

Common Interview Questions

  • ?
    What is the difference between useState and useRef?
  • ?
    When would you use useRef instead of useState?
  • ?
    How can useRef help with performance optimization?
  • ?
    What happens when you update a ref value?
  • ?
    How do you access the current DOM element with useRef?