React JS useRef Hook


The useRef hook in React is used to create and manage mutable references to DOM elements or values within functional components. Unlike state, updates to a ref do not trigger a re-render, making useRef useful for cases where you need to keep track of a value or reference without affecting the rendering lifecycle.

Key Concepts of useRef

  1. Creating a Ref:

    • useRef is called with an initial value and returns a mutable object with a current property.
    • Syntax:
      const myRef = useRef(initialValue);
    • Example:
      import React, { useRef } from 'react'; function MyComponent() { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); } export default MyComponent;
  2. Accessing DOM Elements:

    • useRef is commonly used to access and manipulate DOM elements directly, such as focusing an input field or measuring the dimensions of an element.
    • Example:
      import React, { useRef, useEffect } from 'react'; function MyComponent() { const divRef = useRef(null); useEffect(() => { console.log(divRef.current.getBoundingClientRect()); }, []); return <div ref={divRef}>Hello, World!</div>; } export default MyComponent;
  3. Storing Mutable Values:

    • useRef can also be used to store mutable values that do not require triggering a re-render when they change. This is useful for keeping track of values across renders without causing performance issues.
    • Example:
      import React, { useRef, useState } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); const countRef = useRef(0); const increment = () => { countRef.current += 1; setSeconds(countRef.current); }; return ( <div> <p>Seconds: {seconds}</p> <button onClick={increment}>Increment</button> </div> ); } export default Timer;
  4. Avoiding Re-renders:

    • Unlike state variables, changing a ref does not trigger a re-render of the component. This makes useRef ideal for storing values that should persist across renders but do not need to cause re-renders.
    • Example:
      import React, { useRef, useState } from 'react'; function Example() { const [count, setCount] = useState(0); const renderCount = useRef(0); renderCount.current += 1; return ( <div> <p>Current Count: {count}</p> <p>Render Count: {renderCount.current}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Example;
  5. Common Use Cases:

    • DOM Manipulation: Accessing and manipulating DOM elements directly.
    • Persisting Values: Storing values across renders without causing re-renders.
    • Managing Previous Values: Keeping track of previous values for comparison or other purposes.

Summary

  • useRef: A React hook that provides a way to create mutable references to DOM elements or values without triggering re-renders.
  • Creating a Ref: const ref = useRef(initialValue);
  • Accessing DOM Elements: Useful for direct manipulation or measurements of DOM elements.
  • Storing Mutable Values: Ideal for values that should persist but do not require causing re-renders.
  • Avoiding Re-renders: Changes to refs do not trigger component re-renders.

The useRef hook is a versatile tool in React that allows for efficient DOM manipulation and value persistence while avoiding unnecessary re-renders, helping to optimize the performance and manageability of functional components.