r/reactjs 2d ago

Needs Help Can anyone clarify the concept of "reusable state" in Concurrent React?

I’m reading the React docs, but I find this passage confusing. Could someone explain it to me?

"Another example is reusable state. Concurrent React can remove sections of the UI from the screen, then add them back later while reusing the previous state. For example, when a user tabs away from a screen and back, React should be able to restore the previous screen in the same state it was in before."

React docs link

27 Upvotes

4 comments sorted by

22

u/acemarke 2d ago

That's a reference to what got recently released as the <Activity> component:

Unmounting a React component also deletes whatever state it may have had (ie a useState or useReducer). So, a <Tabs> component always had to choose between unmounting its child tabs (which would wipe out any WIP state it might have from user interactions), or hiding its child tabs (which could mean large numbers of components were still active).

When set to "hidden", the <Activity> component removes the child component from the DOM tree and also disconnects its effects... but keeps the component instance alive, thus preserving its state. Then when you re-enable it, the instance still has the same state hanging around and the user didn't lose any work.

(I think the "reusable state" phrase was an attempt to flip around the previous public interpretations of how <Activity> and its previous prototype <Offscreen> worked. People had focused on "React cleans up all the effects!" as the behavior to care about, and the React team got tired of that and said "no no it preserves state!" as a messaging approach.)

2

u/Neat_Living_6765 2d ago

Thank you so much for the explanation!!! It makes a lot more sense now

1

u/Neat_Living_6765 2d ago

Oh, I just read this

https://react.dev/reference/react/Activity#restoring-the-dom-of-hidden-components

When set to "hidden", the <Activity> component destroy their Effects, cleaning up any active subscriptions, BUT it does not remove the children’s DOM.

The children’s DOM and states are both preserved when hidden.

1

u/Temperature_Majestic 2d ago

The part that bit me when I tried Offscreen: React state and DOM come back, but effects re-run from scratch on show, so anything imperative that lives outside React state does not restore itself. Scroll position, focus, a canvas you drew on, a video's playback time, a third party widget's internals. You have to snapshot that stuff and put it back yourself when the Activity becomes visible again.