Pie Logo
DOM Interactions - useRef
by Tomas Trescak

PresentationInteractive, narrated presentation of the section content.

ContentDetailed description of the section content.

Understanding useRef in React

The useRef hook in React provides a way to persist values across renders without causing a re-render. It is primarily used for:

  1. Accessing DOM elements (like input fields or divs).
  2. Storing mutable values that do not trigger re-renders.

Key Points About useRef

  • useRef returns a mutable object with a current property:
     

    const myRef = useRef(initialValue);
    
  • The current property can hold:
    • A DOM element reference.
    • A mutable value that persists across renders.

Example 1: Accessing DOM Elements

This is the most common use case for useRef.

Code Example:

import React, { useRef, useEffect } from "react";

const DomRefDemo = () => {
  const inputRef = useRef(null);

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

  return (
    <div>
      <h1>useRef Example: DOM Access</h1>
      <input ref={inputRef} type="text" placeholder="I will be focused on load" />
    </div>
  );
};

export default DomRefDemo;

How It Works:

  1. useRef(null) creates a reference object.
  2. The ref attribute assigns the DOM node to inputRef.current.
  3. In useEffect, inputRef.current.focus() focuses the input field.

Example 2: Storing Mutable Values Without Re-rendering

You can use useRef to store a value that does not trigger re-renders when updated.

Code Example:

import React, { useRef, useState } from "react";

const MutableRefDemo = () => {
  const renderCount = useRef(1);
  const [count, setCount] = useState(0);

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

  return (
    <div>
      <h1>useRef Example: Mutable Values</h1>
      <p>Component Re-rendered: {renderCount.current} times</p>
      <p>State Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
    </div>
  );
};

export default MutableRefDemo;

How It Works:

  1. useRef holds the value of renderCount and persists it across renders.
  2. Updating renderCount.current does not trigger a re-render.
  3. Clicking the button only triggers a re-render due to state (setCount), and renderCount continues to persist.

Example 3: Preserving Previous State or Value

You can use useRef to store the previous value of a prop or state.

Code Example:

import React, { useEffect, useRef, useState } from "react";

const PreviousValueDemo = () => {
  const [count, setCount] = useState(0);
  const prevCount = useRef(count);

  useEffect(() => {
    prevCount.current = count; // Update the ref value after render
  }, [count]);

  return (
    <div>
      <h1>useRef Example: Preserve Previous State</h1>
      <p>Current Count: {count}</p>
      <p>Previous Count: {prevCount.current}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default PreviousValueDemo;

How It Works:

  1. useRef stores the previous value of count.
  2. useEffect updates prevCount.current after every render.
  3. The previous value persists across renders without causing additional updates.

When to Use <strong>useRef</strong>

  1. Accessing DOM elements: For direct manipulation of DOM nodes.
  2. Storing values: To persist mutable values across renders without triggering re-renders.
  3. Tracking previous values: Store and retrieve prior state/props.

Key Differences Between useRef and useState:

FeatureuseRefuseState
Triggers Re-render❌ No✅ Yes
Mutable✅ Yes (via current)✅ Yes (but causes re-render)
UsageDOM access, persisting valuesState management, triggering re-renders

Summary

  • useRef is versatile for DOM access, storing values, and tracking previous states.
  • It helps optimize performance by avoiding unnecessary re-renders.

Let me know if you need more examples or further explanation! 🚀

Discuss with OthersAsk questions, share your thoughts, and discuss with other learners.

Loading discussion ...
Full Stack Development
Introduction
Generative AI
🍰 Player
💼 Editor
Setup
React Fundamentals
Next.js
Advanced React
Pure Components - memo
Lifecycle - useEffect
Expensive? - useMemo
DOM Interactions - useRef
Exercise: useRef
Quiz: useRef
Error Boundaries
Context
Leaderboards
Databases
React Hooks
Authentication and Authorisation
APIs
CI/CD and DevOps
Testing React
Advanced Topics
    Pie Logo
    DOM Interactions - useRef
    by Tomas Trescak

    PresentationInteractive, narrated presentation of the section content.

    ContentDetailed description of the section content.

    Understanding useRef in React

    The useRef hook in React provides a way to persist values across renders without causing a re-render. It is primarily used for:

    1. Accessing DOM elements (like input fields or divs).
    2. Storing mutable values that do not trigger re-renders.

    Key Points About useRef

    • useRef returns a mutable object with a current property:
       

      const myRef = useRef(initialValue);
      
    • The current property can hold:
      • A DOM element reference.
      • A mutable value that persists across renders.

    Example 1: Accessing DOM Elements

    This is the most common use case for useRef.

    Code Example:

    import React, { useRef, useEffect } from "react";
    
    const DomRefDemo = () => {
      const inputRef = useRef(null);
    
      useEffect(() => {
        // Focus the input field on component mount
        inputRef.current.focus();
      }, []);
    
      return (
        <div>
          <h1>useRef Example: DOM Access</h1>
          <input ref={inputRef} type="text" placeholder="I will be focused on load" />
        </div>
      );
    };
    
    export default DomRefDemo;
    

    How It Works:

    1. useRef(null) creates a reference object.
    2. The ref attribute assigns the DOM node to inputRef.current.
    3. In useEffect, inputRef.current.focus() focuses the input field.

    Example 2: Storing Mutable Values Without Re-rendering

    You can use useRef to store a value that does not trigger re-renders when updated.

    Code Example:

    import React, { useRef, useState } from "react";
    
    const MutableRefDemo = () => {
      const renderCount = useRef(1);
      const [count, setCount] = useState(0);
    
      // Increment renderCount on each re-render
      renderCount.current += 1;
    
      return (
        <div>
          <h1>useRef Example: Mutable Values</h1>
          <p>Component Re-rendered: {renderCount.current} times</p>
          <p>State Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment Count</button>
        </div>
      );
    };
    
    export default MutableRefDemo;
    

    How It Works:

    1. useRef holds the value of renderCount and persists it across renders.
    2. Updating renderCount.current does not trigger a re-render.
    3. Clicking the button only triggers a re-render due to state (setCount), and renderCount continues to persist.

    Example 3: Preserving Previous State or Value

    You can use useRef to store the previous value of a prop or state.

    Code Example:

    import React, { useEffect, useRef, useState } from "react";
    
    const PreviousValueDemo = () => {
      const [count, setCount] = useState(0);
      const prevCount = useRef(count);
    
      useEffect(() => {
        prevCount.current = count; // Update the ref value after render
      }, [count]);
    
      return (
        <div>
          <h1>useRef Example: Preserve Previous State</h1>
          <p>Current Count: {count}</p>
          <p>Previous Count: {prevCount.current}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    };
    
    export default PreviousValueDemo;
    

    How It Works:

    1. useRef stores the previous value of count.
    2. useEffect updates prevCount.current after every render.
    3. The previous value persists across renders without causing additional updates.

    When to Use <strong>useRef</strong>

    1. Accessing DOM elements: For direct manipulation of DOM nodes.
    2. Storing values: To persist mutable values across renders without triggering re-renders.
    3. Tracking previous values: Store and retrieve prior state/props.

    Key Differences Between useRef and useState:

    FeatureuseRefuseState
    Triggers Re-render❌ No✅ Yes
    Mutable✅ Yes (via current)✅ Yes (but causes re-render)
    UsageDOM access, persisting valuesState management, triggering re-renders

    Summary

    • useRef is versatile for DOM access, storing values, and tracking previous states.
    • It helps optimize performance by avoiding unnecessary re-renders.

    Let me know if you need more examples or further explanation! 🚀

    Discuss with OthersAsk questions, share your thoughts, and discuss with other learners.

    Loading discussion ...
    Full Stack Development
    Introduction
    Generative AI
    🍰 Player
    💼 Editor
    Setup
    React Fundamentals
    Next.js
    Advanced React
    Pure Components - memo
    Lifecycle - useEffect
    Expensive? - useMemo
    DOM Interactions - useRef
    Exercise: useRef
    Quiz: useRef
    Error Boundaries
    Context
    Leaderboards
    Databases
    React Hooks
    Authentication and Authorisation
    APIs
    CI/CD and DevOps
    Testing React
    Advanced Topics
    Pie Logo
    DOM Interactions - useRef
    by Tomas Trescak

    No hints available.

    Full Stack Development
    Introduction
    Generative AI
    🍰 Player
    💼 Editor
    Setup
    React Fundamentals
    Next.js
    Advanced React
    Pure Components - memo
    Lifecycle - useEffect
    Expensive? - useMemo
    DOM Interactions - useRef
    Exercise: useRef
    Quiz: useRef
    Error Boundaries
    Context
    Leaderboards
    Databases
    React Hooks
    Authentication and Authorisation
    APIs
    CI/CD and DevOps
    Testing React
    Advanced Topics
    Pie Logo
    DOM Interactions - useRef
    by Tomas Trescak

    No hints available.

    Full Stack Development
    Introduction
    Generative AI
    🍰 Player
    💼 Editor
    Setup
    React Fundamentals
    Next.js
    Advanced React
    Pure Components - memo
    Lifecycle - useEffect
    Expensive? - useMemo
    DOM Interactions - useRef
    Exercise: useRef
    Quiz: useRef
    Error Boundaries
    Context
    Leaderboards
    Databases
    React Hooks
    Authentication and Authorisation
    APIs
    CI/CD and DevOps
    Testing React
    Advanced Topics