Gancio di useRefreazione


L' useRefHook ti consente di mantenere i valori tra i rendering.

Può essere utilizzato per memorizzare un valore mutabile che non provoca un nuovo rendering quando viene aggiornato.

Può essere utilizzato per accedere direttamente a un elemento DOM.


Non causa re-rendering

Se provassimo a contare quante volte la nostra applicazione esegue il rendering usando useStateHook, saremmo presi in un ciclo infinito poiché questo stesso Hook provoca un re-rendering.

Per evitare ciò, possiamo usare il useRefgancio.

Esempio:

Utilizzare useRefper tenere traccia dei rendering delle applicazioni.

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

function App() {
  const [inputValue, setInputValue] = useState("");
  const count = useRef(0);

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

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h1>Render Count: {count.current}</h1>
    </>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

useRef()restituisce solo un articolo. Restituisce un oggetto chiamato current.

Quando inizializziamo useRefimpostiamo il valore iniziale: useRef(0).

È come fare così: const count = {current: 0}. Possiamo accedere al conteggio usando count.current.

Eseguilo sul tuo computer e prova a digitare l'input per vedere aumentare il conteggio del rendering dell'applicazione.


w3schools CERTIFIED . 2022

Ottieni la certificazione!

Completa i moduli React, fai gli esercizi, fai l'esame e diventa certificato w3schools!!

ISCRIVITI A $95

Accesso agli elementi DOM

In generale, vogliamo lasciare che React gestisca tutte le manipolazioni DOM.

Ma ci sono alcuni casi in cui useRefpuò essere utilizzato senza causare problemi.

In React, possiamo aggiungere un refattributo a un elemento per accedervi direttamente nel DOM.

Esempio:

Utilizzare useRefper mettere a fuoco l'input:

import { useRef } from "react";
import ReactDOM from "react-dom";

function App() {
  const inputElement = useRef();

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

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

ReactDOM.render(<App />, document.getElementById('root'));


Monitoraggio dei cambiamenti di stato

L' useRefHook può essere utilizzato anche per tenere traccia dei valori di stato precedenti.

Questo perché siamo in grado di mantenere useRefi valori tra i rendering.

Esempio:

Utilizzare useRefper tenere traccia dei valori di stato precedenti:

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

function App() {
  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");

  useEffect(() => {
    previousInputValue.current = inputValue;
  }, [inputValue]);

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
    </>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

Questa volta utilizziamo una combinazione di useState, useEffect, e useRefper tenere traccia dello stato precedente.

In useEffect, stiamo aggiornando il useRefvalore corrente ogni volta inputValueche viene aggiornato inserendo il testo nel campo di input.