Request for clarification: can ref initialization code (lazy or not) contain side effects?
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:
const playerRef = useRef(new VideoPlayer());
const playerRef = useRef(null);
if (playerRef.current === null) {
playerRef.current = new VideoPlayer();
}
Even the old docs have similar examples:
const ref = useRef(new IntersectionObserver(onIntersect));
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()andnew IntersectionObserver(onIntersect)to contain side effects?
It would be helpful if the docs clarified this.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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