reactjs / react.dev

The React documentation website
https://react.dev/
Creative Commons Attribution 4.0 International
11k stars 7.51k forks source link

[Suggestion]: How to avoid null checks when initializing useRef later #7041

Open pailhead opened 2 months ago

pailhead commented 2 months ago

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.