Debug School

rakesh kumar
rakesh kumar

Posted on

Powerful Applications of React’s useRef Hook

Use of Useref
10 Real Time Application Of useRef

The useRef hook in React is used to create a mutable reference that persists across component renders without causing re-renders when updated. It is commonly used for:

Accessing DOM elements directly

Storing mutable values that don’t require a re-render when changed

Tracking previous state or props

When you call useRef(initialValue), it returns an object with a single property: current. This object stays the same between renders, so you can safely store values on it.

import React, { useRef } from 'react';

function App() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current.focus(); // Access the DOM node directly
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus the input</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, clicking the button will focus the input field by directly accessing the DOM element via inputRef.current.

Other Common Use Cases

  1. Persisting Values Across Renders Without Causing Re-renders
import React, { useState, useRef } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = useRef(count);

  React.useEffect(() => {
    prevCount.current = count;
  }, [count]);

  return (
    <div>
      <p>Now: {count}, Before: {prevCount.current}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here, prevCount.current always holds the previous value of count.

Key Points:

useRef does not cause a re-render when its value changes.

It is ideal for storing values that should persist across renders but don’t need to trigger a UI update.

Focusing DOM Elements
Tracking Previous State
Managing Intervals/Timers
Third-Party Library Integration
Measuring Element Dimensions
Storing Mutable Values
Controlling Animations
Form Validation Focus
Custom Hooks for State History
Caching Expensive Calculations
set values and id in react js
Hide dropdown

Focusing DOM Elements
Use Case: Auto-focus input fields on page load.

import { useRef, useEffect } from 'react';

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

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

  return <input ref={emailRef} placeholder="Email" />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Tracking Previous State Use Case: Compare current and previous values.
import { useState, useRef, useEffect } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef(count);

  useEffect(() => {
    prevCountRef.current = count;
  }, [count]);

  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCountRef.current}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  1. Managing Intervals/Timers Use Case: Polling APIs or stopwatch timers.
import { useRef, useEffect } from 'react';

function Timer() {
  const timerRef = useRef();

  useEffect(() => {
    timerRef.current = setInterval(() => {
      console.log('Tick');
    }, 1000);

    return () => clearInterval(timerRef.current); // Cleanup
  }, []);

  return <p>Check console for timer ticks.</p>;
}
Enter fullscreen mode Exit fullscreen mode
  1. Third-Party Library Integration Use Case: Attach D3.js or Chart.js to a DOM node.
import { useRef, useEffect } from 'react';

function Chart() {
  const chartRef = useRef();

  useEffect(() => {
    // Initialize chart library here
    new ChartJS(chartRef.current, { data: /* ... */ });
  }, []);

  return <div ref={chartRef} />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Measuring Element Dimensions Use Case: Responsive layouts based on element size.
import { useRef, useEffect } from 'react';

function ResponsiveBox() {
  const boxRef = useRef();

  useEffect(() => {
    const width = boxRef.current.offsetWidth;
    console.log('Box width:', width);
  }, []);

  return <div ref={boxRef} style={{ width: '50%' }} />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Storing Mutable Values Use Case: Track renders without re-rendering.
import { useRef, useEffect } from 'react';

function RenderCounter() {
  const renderCount = useRef(0);

  useEffect(() => {
    renderCount.current += 1;
  });

  return <p>Renders: {renderCount.current}</p>;
}
Enter fullscreen mode Exit fullscreen mode
  1. Controlling Animations Use Case: Canvas/GSAP animations.
import { useRef, useEffect } from 'react';

function CanvasAnimation() {
  const animationRef = useRef();

  useEffect(() => {
    const animate = () => {
      // Animation logic
      animationRef.current = requestAnimationFrame(animate);
    };
    animate();

    return () => cancelAnimationFrame(animationRef.current);
  }, []);

  return <canvas />;
}
Enter fullscreen mode Exit fullscreen mode
  1. Form Validation Focus Use Case: Highlight invalid fields.
import { useRef, useState } from 'react';

function LoginForm() {
  const emailRef = useRef();
  const [error, setError] = useState('');

  const handleSubmit = () => {
    if (!emailRef.current.value) {
      emailRef.current.focus(); // Focus on error
      setError('Email required');
    }
  };

  return (
    <div>
      <input ref={emailRef} />
      {error && <p>{error}</p>}
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  1. Custom Hooks for State History Use Case: Reusable undo/redo logic.
import { useState, useEffect, useRef } from 'react';

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

// Usage:
function App() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  // ...
}
Enter fullscreen mode Exit fullscreen mode
  1. Caching Expensive Calculations Use Case: Memoize heavy computations.
import { useRef } from 'react';

function HeavyComponent() {
  const cachedResult = useRef();

  if (!cachedResult.current) {
    cachedResult.current = heavyCalculation(); // Runs once
  }

  return <p>Result: {cachedResult.current}</p>;
}
Enter fullscreen mode Exit fullscreen mode

11.set values and id in react js

import React, { useRef } from 'react';

function MyForm() {
  const usernameRef = useRef();
  const passwordRef = useRef();

  const handleSubmit = (e) => {
    e.preventDefault();

    const username = usernameRef.current.value;
    const password = passwordRef.current.value;

    // Perform authentication logic using username and password
    // ...
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          ref={usernameRef}
          placeholder="Username"
        />
        <input
          type="password"
          ref={passwordRef}
          placeholder="Password"
        />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

12.Hide dropdown

import React, { useState, useRef, useEffect } from "react";
Enter fullscreen mode Exit fullscreen mode
  const dropdownRef = useRef(null);
Enter fullscreen mode Exit fullscreen mode
  useEffect(() => {
    function handleClickOutside(event) {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target)
      ) {
        setIsDropdownVisible(false);
      }
    }
    if (isDropdownVisible) {
      document.addEventListener("mousedown", handleClickOutside);
    } else {
      document.removeEventListener("mousedown", handleClickOutside);
    }
    // Cleanup
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isDropdownVisible]);
Enter fullscreen mode Exit fullscreen mode
<div className="location-search-box" ref={dropdownRef}>
            <input
              type="text"
              name="location"
              className="search-dropdown"
              value={location}
              placeholder="Select or Search the City"
              onChange={handleLocationChange}
              onClick={() => setIsDropdownVisible(true)} // Show dropdown on click
              required
              style={{
                padding: "10px 15px",
                borderRadius: "25px",
                border: "1px solid #ccc",
                marginBottom: "15px",
                fontSize: "16px",
                width: '100%',
              }}
            />
            {isDropdownVisible && (
              <div className="dropdown-list" style={{
                position: "absolute",
                zIndex: "999",
                backgroundColor: "white",
                border: "1px solid #ccc",
                borderRadius: "5px",
                width: "100%",
                marginTop: "5px",
                maxHeight: "150px",
                overflowY: "auto",
              }}>
                {filteredLocations.length > 0 ? (
                filteredLocations.map((loc, index) => (
                  <div
                    key={index}
                    className="dropdown-item"
                    onClick={() => {
                      setLocation(loc.city);
                      setIsDropdownVisible(false);
                    }}
                    style={{
                      padding: "8px",
                      cursor: "pointer",
                    }}
                  >
                    {sanitizeInput(loc.city)} {/* Display sanitized city */}
                  </div>
                ))
              ) : (
                <div className="dropdown-item" style={{ padding: "8px" }}>
                  No cities found
                </div>
              )}
              </div>)}
          </div>
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)