Skip to content

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

@gmoniava

Description

@gmoniava

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions