react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

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

Open gmoniava opened this issue 4 months ago • 0 comments

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.

gmoniava avatar Sep 06 '25 08:09 gmoniava