In my app I have multiple contexts for managing and storing state.
In one of my scenarios, I have noticed that, as I have a UsersContext (which stores the users data), it is not necessary to store the user data of each post creator in my PostsContext, it could be better (for RAM) to just store its user id, and not to repeat the user data on it.
I have thought to use "parsers" inside my reducers logic before storing data, in order to remove the unnecessary fields of each object.
Is this a good idea / is a common pattern?
The main problem I notice with this approach is: how to get the data correctly from both contexts? I mean, imagine the following component:
function Card({ content: { userData, image, description, location, date }) {
...
}
If I want to get the data from the contexts, and not from props, I have implemented two custom hooks (do not care about memoizations right now) which consumes a specific context:
/* HOOKS FOR GETTING SPECIFIC DATA FROM CONTEXT */
function useUpdatedPostData(postData) {
const posts = usePosts(); <-- consume PostsContext
return {
...postData,
...posts.getPost(postData.id) <--- Merging with data from context
}
}
function useUpdatedUserData(userData) {
const users = useUsers(); <-- consume UsersContext
return {
...userData,
...users.getUser(userData.id) <--- Merging with data from context
}
}
/* CONSUMER COMPONENT */
function Card({ content }) {
// The main problem:
const {
image,
description,
location,
date,
} = useUpdatedPostData(content);
const { username, avatar } = useUpdatedUserData(content.userData);
...
}
something which makes the code really difficult to read. Any tips?