Introduction
In am implementing an Instagram clone:
- Users have posts.
- Posts can be liked.
- Users can comment in posts.
- Posts have a totalLikes and totalComments field.
- Comments can be liked.
- Users can reply to comments.
- Comments have a totalLikes and totalComments (replies) field.
Until now, I have been working with the current PostsContext:
const initialState = {};
export function PostsProvider({ children }) {
const [contents, dispatch] = useReducer(contentsReducer, initialState);
const addUserPosts = (userId, posts, unshift = false, cached = true) => { ... }
const likePost = (postOwnerId, postId) => { ... }
const commentPost = (postOwnerId, postId, comment) => { ... }
const getUserPosts = (userId) => { ... }
const getUserPost = (userId, postId) => { ... }
}
Where, my stateful data looks like:
{
userId1: {
posts: [
{
id,
uri,
totalLikes,
totalComments,
isLiked,
date
},
...
]
},
userId2: { posts: [...] }
}
Question
My question is, should I use another context for comments? I mean, comments will work the same way as posts, they can be liked and replied... so maybe, it is unnecessary.
When a user comments in a post:
1. The post totalComments is increased.
2. If the user is replying to a comment in the post, the replied comment's totalComments is increased too.
When a user likes a comment, it doesn't affect to the post "data" itself, only to the liked comment totalLikes field.
So... if I create a new context for comments, it seems that I will need to consume the PostsContext inside it, in order to increase the post totalComments field.
Any ideas about how to structure my posts context?
Note: My question is more about the context organization than anything else (do not look at implementation, just to the structure of my stateful data and the idea of splitting contexts).
CodePudding user response:
There are trade-offs. With multiple contexts you have the option of having a component rendered within a single context, thus reducing refreshes (increasing performance) when another context changes.
However, if most of your components need access to multiple contexts, it may work better to have a "store" (single app-level context). If you're using the selector pattern (which is not just for Redux), then a selector can compute data that would otherwise be in multiple contexts.
I am working on a project with multiple contexts, and regularly think about combining them.
If your project is complex, you may want to consider Redux instead of contexts. It adds complexity but solves some of the issues around organization and combining different areas of the state. If you do that I highly recommend starting with Redux Toolkit to reduce the boilerplate.