[Suggestion]: How to avoid null checks when initializing useRef later
Nessuno ha ancora preso questa issue.
- Lingua principale
- JavaScript
- Stelle
- 11.8k
- Fork
- 7.9k
- Merge medio
- 1g 11h
- PR unite (30g)
- 11
Descrizione
Summary
The example is very bad.
Page
https://react.dev/reference/react/useRef#avoiding-recreating-the-ref-contents
Details
The solution how to avoid this pitfall doesn't seem very robust. If for any reason you wanted to instantiate to VideoPlayer but you want your ref to generally be of type VideoPlayer | null you will never be able to put a null in there.
A more robust way actually seems to leverage useState via:
const [playerRef] = useState(()=>({current:new VideoPlayer()}))
While investigating this issue i've concluded that people in general misunderstand what useRef is, going to the extremes of thinking it's "just for dom elements". playerRef in this snipper is exactly MutableRefObject<VideoPlayer> and this approach doesn't involve all kinds of acrobatics, like lying to a type checker, checks inside the render body etc.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Leggi la documentazione di useRef nella sezione collegata “avoiding recreating the ref contents” e rivedi l’esempio attuale e le relative ipotesi di tipizzazione dichiarate. Confronta l’approccio proposto con useState con le indicazioni esistenti, quindi aggiorna l’esempio o la spiegazione in modo che siano chiari il tipo di ref previsto, il comportamento di null e i compromessi dell’inizializzazione.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, react
- Ambito
- documentation
- Tipo di issue
- Documentazione
- Difficoltà
- 3/5
- Tempo stimato
- 1-2 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100