reactjs / reactjs/react.dev

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

Open
#7,041 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type: documentation
Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read the useRef documentation at the linked “avoiding recreating the ref contents” section and review the current example and its stated typing assumptions. Compare the proposed useState approach with the existing guidance, then update the example or explanation so the intended ref type, null behavior, and initialization trade-offs are clear.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.