Skip to content

Latest commit

 

History

History
96 lines (62 loc) · 3.08 KB

useRef.md

File metadata and controls

96 lines (62 loc) · 3.08 KB

useRef: Accessing DOM Elements and Keeping Mutable References 🔗

Welcome back! Today, we're diving into the useRef hook, a versatile tool in React that helps you manage references and store mutable values without causing re-renders.

What is useRef?

useRef is a React hook that allows you to create a mutable object which holds a .current property. This property can be used to store a reference to a DOM element or any other mutable value.

Mia: "So, what’s the big deal about useRef?"

Leo: "Great question, Mia! It helps us keep track of values and DOM nodes without triggering re-renders, making our app more efficient!" 🚀

Accessing DOM Elements

One of the most common uses of useRef is to access DOM elements directly. Here’s how you can do that:

import React, { useRef } from 'react';

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

  const focusInput = () => {
    inputRef.current.focus(); // Focus the input element
  };

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="Click the button to focus me!" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
};

export default FocusInput;

Explanation:

  1. Creating the Ref:

    • inputRef is created using useRef(null). This ref will hold the reference to the input element.
  2. Using the Ref:

    • By setting the ref attribute of the input element to inputRef, React attaches the input DOM node to this ref.
  3. Focusing the Input:

    • When the button is clicked, the focusInput function calls inputRef.current.focus(), which focuses the input element.

Storing Mutable Values

useRef can also be used to store any mutable value, not just DOM references. This means you can track numbers, strings, or any other values without causing re-renders.

Example: Counting Clicks

const CountClicks = () => {
  const countRef = useRef(0); // Initialize a ref to store the count

  const handleClick = () => {
    countRef.current += 1; // Increment the count
    console.log(`Button clicked ${countRef.current} times`); // Log the current count
  };

  return (
    <div>
      <button onClick={handleClick}>Click Me!</button>
    </div>
  );
};

Explanation:

  1. Creating the Ref:

    • countRef is initialized to 0 to keep track of clicks.
  2. Updating the Ref:

    • Each time the button is clicked, countRef.current is incremented.
  3. No Re-renders:

    • Using a ref here doesn’t trigger a re-render, making it efficient for tracking values.

Mia: "So, I can use useRef for any value, not just for DOM elements?"

Leo: "Exactly! It’s perfect for holding onto values you want to persist without affecting the render cycle." 🎉

Fun Fact! 🎉

Using useRef for tracking counters or timers is particularly beneficial in performance-sensitive applications, as it helps keep your component clean and efficient!


Navigation

Previous: Accessing DOM Elements with useRef | Next: useReducer: Managing Complex State Logic