useRef hook
Conserva valori mutabili tra render e accedi a nodi DOM reali.
Cos'è una ref
useRef restituisce un oggetto stabile con una proprietà current. Puoi modificarla senza provocare un nuovo render.
const inputRef = useRef();È utile quando devi:
- leggere o chiamare metodi su un nodo DOM;
- salvare un id di
setInterval; - conservare una cache o un valore mutabile;
- integrare una libreria esterna che ha il proprio ciclo di vita.
Ref DOM
Passa la ref all'attributo ref. Dopo il render, current contiene il nodo.
function FocusInput() {
const inputRef = useRef();
return html`
<input ref=${inputRef} />
<button @click=${() => inputRef.current.focus()}>
Focus
</button>
`;
}Timer
Una ref è perfetta per salvare dati che non devono apparire nella UI.
function Timer() {
const [time, setTime] = useState(0);
const intervalId = useRef(null);
const start = () => {
intervalId.current = setInterval(() => {
setTime((value) => value + 1);
}, 10);
};
const stop = () => {
clearInterval(intervalId.current);
intervalId.current = null;
};
return html`
<button @click=${start} disabled=${intervalId.current !== null}>Start</button>
<button @click=${stop} disabled=${intervalId.current === null}>Stop</button>
<span>${(time / 100).toFixed(2)}</span>
`;
}Valori non reattivi
Modificare ref.current non aggiorna il DOM. Se un valore deve comparire nella UI, usa useState. Se invece serve solo come supporto interno, usa useRef.
function SubmitButton() {
const lastSubmitAt = useRef(0);
const submit = () => {
const now = Date.now();
if (now - lastSubmitAt.current < 1000) return;
lastSubmitAt.current = now;
save();
};
return html`<button @click=${submit}>Salva</button>`;
}Esempio: input password
Questo esempio usa una ref per leggere e modificare un input reale.
Regole pratiche
- Usa
useRefquando cambiare il valore non deve causare un render. - Non leggere
ref.currentprima che il nodo sia montato. - Pulisci timer e listener con
useEffectquando il componente viene rimosso.
useReducer - Hooks Wompo
Usa useReducer per stato con molte transizioni, logica testabile e aggiornamenti prevedibili.
useSelf - Hooks Wompo
Usa useSelf per leggere o modificare l'elemento host del componente.