vendredi 30 juillet 2021

Best way to share state between tab-view render props without remounting the components when the state changes

I'm using this library (https://github.com/satya164/react-native-tab-view) to create a tabbed view, where each tab represents a category and renders a list of devices with a checkbox to select/deselect them. Since some of these categories overlap the parent component has to keep track of the selectedDevices, so that when you switch between tabs the next one will be affected by the selection made in the previous ones. That wouldn't be a problem, except for the fact that each tab is basically a ScrollView and so it is of the uttermost importance that every time you make a selection it won't unmount and remount, losing the scrolling position.

TabView has a renderScene prop which allows me to render the various screens. If I pass the selectedDevices through a prop in renderScene it will behave like a factory, basically creating a new React Element each time selectedDevices changes and thus triggering a remount.

If there was a way to set the selected devices only when the screen is about to change (because the user tapped on another tab or swiped to it) that would be good enough because despite the remount that wouldn't affect the scroll position, but using a useEffect cleanup function to set the selected devices won't be of any use because changing tab doesn't unmount the component.

The only solution I've thought of is creating a new Context and use it to share the selectedDevices between the various tab screens. This works very well, avoiding any kind of remount altogether, but somehow I don't like because it feels like a bad design.

Can you think of any better solution?

Aucun commentaire:

Enregistrer un commentaire