Home > Net >  React Context - How to structure user posts
React Context - How to structure user posts

Time:10-12

I am implementing an Instagram clone. In my current app, I have two contexts:

  1. UsersContext
  2. PostsContext

In the users context, I store all the users data, and in the other one, I store the posts data (images, dimensions, description, totalLikes, totalComments, and location).

As you can see, I am not storing nothing about the post owner... neither his id, nor his avatar or username... literally there is no data about users in the PostsContext.

In my card component, I am consuming both contexts, in order to synchronize all the UI with the most up-to-date data which is relative to users and posts.

My question is: should I include the posts owners' data inside the PostsContext? Is there any kind of pattern or something? This is my first time using React Context API, I am a little lost. Is the only purpose of contexts to make things globally and synchronize all routes?

Any example?

CodePudding user response:

Generally I would order the providers this way.

<UserContextProvider>
  ...
  <PostContextProvider uid={uid}>
    ...
  </PostContextProvider>
</UserContextProvider>

Where I make a provider function that will look like

export function PostContextProvider({uid, children}) {
  const posts = getPosts(uid);
  return (
    <PostContext.Provider values={{posts}}>
      {children}
    </PostContext.Provider>
  );
}

then access the posts.

  • Related