Maison > interface Web > js tutoriel > le corps du texte

Crochet useRef expliqué

Linda Hamilton
Libérer: 2024-09-28 18:20:03
original
401 Les gens l'ont consulté

useRef Hook Explained

The useRef hook in React is a powerful feature that allows you to create a mutable reference to a DOM element or any other value that persists for the entire lifecycle of a component. Here’s a detailed explanation of how it works, along with its use cases:

What is useRef?

  • Persistent Storage: useRef provides a way to hold a mutable reference that does not trigger a re-render when updated. This is different from state, where updating a state variable will cause the component to re-render.

  • Returns a Mutable Object: When you call useRef(initialValue), it returns a mutable object with a current property that you can modify. The initial value you pass to useRef is set to current, but you can change current at any time.

Basic Syntax

const myRef = useRef(initialValue);
Copier après la connexion

Example of useRef

Here’s a simple example where useRef is used to access a DOM element:

import React, { useRef } from 'react';

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

  const focusInput = () => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

export default FocusInput;
Copier après la connexion

Explanation of the Example

  1. Creating a Ref: const inputRef = useRef(null); creates a reference to hold a reference to the input element.

  2. Assigning the Ref: The ref attribute of the input element is assigned to inputRef. This allows React to attach the input DOM element to the current property of inputRef.

  3. Accessing the Ref: When the button is clicked, the focusInput function accesses the input element through inputRef.current and calls focus() on it.

Use Cases

  1. Accessing DOM Elements: As shown in the example, useRef is commonly used to access and interact with DOM elements directly.

  2. Storing Mutable Values: You can use useRef to store any mutable value that doesn’t require re-rendering when changed, such as a timer ID or a previous value.

   const timerRef = useRef();

   const startTimer = () => {
     timerRef.current = setTimeout(() => {
       // some action
     }, 1000);
   };

   const stopTimer = () => {
     clearTimeout(timerRef.current);
   };
Copier après la connexion
  1. Persisting Values Across Renders: Unlike state, a value held in useRef does not reset on re-renders. This can be useful for keeping track of values that are used in callbacks or effects.

  2. Integrating with Third-party Libraries: When using third-party libraries that manipulate the DOM directly, useRef can provide a way to keep a reference to those DOM nodes.

Comparison with useState

  • Re-renders: Updating a state variable with useState will trigger a re-render of the component, while updating a useRef will not.

  • Storage: Use useRef for values that do not affect the rendering of the component, whereas useState should be used for values that do.

Key Points to Remember

  • useRef can hold any value, not just DOM elements.
  • The current property can be updated freely without causing a re-render.
  • Ideal for accessing DOM nodes or storing mutable values that don’t need to trigger a render.

By understanding these concepts, you can effectively utilize the useRef hook in your React applications! If you have any specific use cases or questions about useRef, feel free to ask!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!