Using Ref - anastasiamexa/react-complete-guide-course-resources GitHub Wiki

The useRef hook in React is a Hook that provides a way to create mutable object properties that persist across renders. It is commonly used for accessing and interacting with a DOM element or for persisting values across renders without causing re-renders.

Here's a basic overview of how useRef works:

1. Creating a Ref:
You can create a ref using the useRef function:

import { useRef } from 'react';

const myRef = useRef(initialValue);

initialValue is an optional argument that can be used to set an initial value for the ref.

2. Accessing DOM Elements:
One common use case for useRef is to access the DOM elements directly. For example:

import { useRef, useEffect } from 'react';

function MyComponent() {
  const myInputRef = useRef(null);

  useEffect(() => {
    // Focus on the input element when the component mounts
    myInputRef.current.focus();
  }, []);

  return <input ref={myInputRef} />;
}

In this example, the ref attribute is used to assign the myInputRef to the input element. Later, within the useEffect hook, we use myInputRef.current to reference the actual DOM element and call the focus method.

3. Persisting Values Without Rerendering:
Another use case is to persist values across renders without causing a re-render:

import { useRef, useState } from 'react';

function MyComponent() {
  const renderCount = useRef(0);
  const [state, setState] = useState(0);

  renderCount.current = renderCount.current + 1;

  return (
    <div>
      <p>Render Count: {renderCount.current}</p>
      <button onClick={() => setState(state + 1)}>Increment State</button>
    </div>
  );
}

In this example, renderCount is a ref that persists across renders, and it's updated without causing a re-render when the component re-renders.

Remember that changes to the current property of a ref don't trigger a re-render. It's important to note that while useRef can be used for persisting values, it doesn't cause the component to re-render when the ref's value changes. If you need to trigger a re-render when a value changes, consider using useState or useReducer.

Example

import { useState, useRef } from "react";

export default function Player() {
  // Create a ref to store a reference to the input element
  const playerName = useRef();

  // Create a state variable to store the entered player name
  const [enteredPlayerName, setEnteredPlayerName] = useState(null);

  // Function to handle the button click
  function handleClick() {
    // Set the enteredPlayerName state to the value of the input element
    setEnteredPlayerName(playerName.current.value);

    // Clear the input field by setting its value to an empty string
    playerName.current.value = '';
  }

  // Display the welcome message with the entered player name (or 'unknown entity' if no name)
  return (
    <section id="player">
      <h2>Welcome {enteredPlayerName ?? 'unknown entity'}</h2>
      <p>
        {/* Input element with a ref assigned to playerName */}
        <input ref={playerName} type="text"/>
        {/* Button with onClick event handler set to handleClick function */}
        <button onClick={handleClick}>Set Name</button>
      </p>
    </section>
  );
}

Explanation:

  • const playerName = useRef();: This line creates a ref using the useRef hook and assigns it to the variable playerName. This ref is then used to store a reference to the input element.

  • <input ref={playerName} type="text"/>: In the JSX, the ref attribute is set to the playerName ref. This means that playerName.current will refer to the actual DOM node of the input element. This is useful for accessing the input value without causing a re-render of the component.

  • function handleClick() {...}: In the handleClick function, playerName.current.value is used to get the value of the input element. This value is then set as the new state using setEnteredPlayerName. After that, the input field is cleared by setting its value to an empty string (playerName.current.value = '').

By using useRef in this way, you can efficiently access and manipulate the DOM element without triggering unnecessary re-renders of the component. This is particularly useful when you need to work with values in the DOM directly.

State vs Ref

useState and useRef are both hooks in React, but they serve different purposes, and understanding their differences is crucial for using them effectively.

State

Purpose:

  • useState is used to declare state variables in functional components.
  • It triggers a re-render when the state is updated, causing the component to reflect the new state.

Usage:

  • useState returns an array with two elements: the current state value and a function to update the state.

Ref

Purpose:

  • useRef is used to persist values across renders without causing re-renders.
  • It does not trigger a re-render when the ref's value changes.
  • It is commonly used to store and access mutable values, or to get references to DOM elements.

Usage:

  • useRef returns an object with a current property that can be assigned to a DOM element or any mutable value.

When to Use Each One

Use useState when:

  • You need to manage and update the state of your component.
  • Changes to the state should trigger a re-render of the component.
  • You want to maintain stateful values that affect the component's appearance.

Use useRef when:

  • You want to persist values across renders without causing re-renders.
  • You need to get references to DOM elements.
  • You want to store mutable values that don't trigger re-renders.
⚠️ **GitHub.com Fallback** ⚠️