reactjs / reactjs/react.dev

Request for clarification: can ref initialization code (lazy or not) contain side effects?

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

Nobody has claimed this yet.

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

Description

New docs on avoiding recreating ref contents has two examples:

Example1:

const playerRef = useRef(new VideoPlayer());

Example2:

const playerRef = useRef(null);
if (playerRef.current === null) {
  playerRef.current = new VideoPlayer();
}

Even the old docs have similar examples:

Example3:

const ref = useRef(new IntersectionObserver(onIntersect));

Example4:

const ref = useRef(null);
if (ref.current === null) {
   ref.current = new IntersectionObserver(onIntersect);
}

Both new VideoPlayer() and new IntersectionObserver(onIntersect) look like calls that might contain side effects inside.
My question is it allowed in any of the above examples, for these calls to contain side effects?

  • imho in Examples 1/3 they should not because they are executed on each render; although only values from initial render are kept.

  • But examples 2/4 suggest a pattern which make reading and writing to refs ok - which normally is an impure operation already. So I thought maybe in those examples at least, it is ok for new VideoPlayer() and new IntersectionObserver(onIntersect) to contain side effects?

It would be helpful if the docs clarified this.

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

Start with the current useRef “avoiding recreating the ref contents” section and the linked legacy Hooks FAQ section on creating expensive objects lazily. Compare all four examples and verify the React guidance on render-time side effects. Done means the documentation clearly explains whether these initialization patterns may contain side effects and distinguishes their behavior.

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
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.