Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
React Context Provider as near from consumers as possible

Introduction

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"

Question

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?

My idea

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)

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!