reactjs / reactjs/react.dev

React 18 concurrent instantiation and disposal

Open
#6,283 4 comments 1 reaction 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

Hi there!

I have been reflecting on what React 18 concurrent mode means for instantiation and disposal of objects returning state.

So something you could do before React 18 and StrictMode was:

const SomeComponent = () => {
  const ref = useRef()

  if (!ref.current) {
    ref.current = new SomeStateToAccessInComponentRender()
  }

  useEffect(() => {
    return () => ref.current.dispose()
  }, [])
}

But as I understand, with React 18 (spearheaded by StrictMode) you can not really rely on creating instances during "rendering" cause React might call the function body multiple times ,and even abandon it, before mounting and running any effects.

I understand that pure components are necessary for concurrent mode and to me it makes a lot of sense that React is becoming this pure state synchronisation using subscriptions type of implementation. But what does not make sense to me is that there is no way to "create something" when React has the intention of mounting a component and "dispose that something" when React is abandoning the component due to concurrent mode or unmounting it.

I wish there was some explicit documentation/statement that explains you can not rely on React 18 to control the instantiation and disposal of objects and more importantly some guides to how you should actually deal with it.

Which brings me to... have I gotten it wrong? Is there a way to safely do this? And if not, do we now rely on external state stores to determine when to instantiate/dispose of objects?

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

No files or tests are named. Start with the issue's React 18 concurrent-rendering and StrictMode examples, then review the existing documentation for render-time instantiation, effects, and disposal. Done means adding explicit guidance on whether this pattern is safe and how objects should be created and disposed.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation, frontend
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 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.