📊 Capítulo 06: useRef & useId
Especialização em Frontend com React
🗺️ useRef: DOM Node Access vs Instância Mutável Silenciosa
flowchart TD
ROOT["useRef(valorInicial)"]
--> CASE1["1. Acesso a Nó do DOM: <input ref={inputRef} />\n(Foco, medições de bounding box, Canvas 2D/3D)"]
ROOT --> CASE2["2. Variável Mutável Silenciosa: timerRef.current = setInterval(...)\n(Alterar .current NÃO dispara re-renderização da tela!)"]
style ROOT fill:#ede7f6,stroke:#512da8,stroke-width:2px
style CASE1 fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
style CASE2 fill:#fff3e0,stroke:#ff9800,stroke-width:2px
🎯 Slide 1: useRef para Controle de Foco no DOM
const inputBuscaRef = useRef<HTMLInputElement>(null);
function focarBusca() {
inputBuscaRef.current?.focus();
}
return <input ref={inputBuscaRef} type="search" />;
🎯 Slide 2: Armazenando Timers e Valores Prévios
- Como alterar
ref.currentnão causa re-renderização, é o lugar perfeito para guardar IDs desetInterval, instâncias de conexões WebSocket e o valor anterior de uma prop!
🎯 Slide 3: Acessibilidade Blindada com useId
const idUnico = useId();
return (
<>
<label htmlFor={idUnico}>E-mail Corporativo:</label>
<input id={idUnico} type="email" />
</>
);
- Gera identificadores estáveis garantindo zero erros de hidratação (hydration mismatch) entre SSR e cliente!
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim