I have read that, in order to increase React apps performance, it is cool to place Context Providers as near from children as possible.
For example, imagine that you have this context
function UserPostsProvider({ children }) {
const [posts, setPosts] = useState({});
...
return <UserPostsContext.Provider ...
}
which is consumed in two screens: "UserPostsGrid" and UserPostsCardList"
How can I do to place the context provider near both screens without losing the stateful data of the provider?
I mean, this is my current navigation system:
function StackNavigator() {
/*
Local Context Providers
*/
return (
<UserPostsProvider>
<MainStackNavigator />
</UserPostsProvider>
);
}
const MainStackNavigator = memo(() => {
const Stack = createStackNavigator();
return (
<Stack.Navigator>
// ... lot of screens
<Stack.Screen
name="UserPostsGrid"
component={UserPostsGrid}
/>
<Stack.Screen
name="UserPostsCardList"
component={UserPostsCardList}
/>
</Stack.Navigator>
);
}, ...);
How can I do for sharing this context (without un-mounting it and losing its data) between all the instances of UserPostsGrid and UserPostsCardList screens?
I have thought to encapsulate the screens inside the UserPostsProvider as follows
function UserPostsGrid(...) {
return <UserPostsProvider> ...screen data </UserPostsProvider>
}
function UserPostsCardList(...) {
return <UserPostsProvider> ...screen data </UserPostsProvider>
}
I haven test it yet, but I feel that the provider can be unmounted when the stack screen is closed and that there are two different instances of it (state is not shared then)