I have a small app with the following structure Posts -> Post -> Comments -> Comment.
The Posts component makes a request for an array of sorted posts by date (DESC). Each posts has its comments (which come through another request).
The problem I am facing. When I add a new item in the beginning of the posts array in order to keep it ordered and display the newest one, the entire component tree updates -> Post Component -> Comments Component, therefore for all the currently existing posts on the page, there will be again a request to get their comments even though they already have them.
If I add it in the end of the array, this does not happen, but if I sort them using a useMemo hook or something, the behavior described starts again
Anyone has any idea how I can get over this?
Part of the code is like this
{sortedPosts && sortedPosts.map((post, index) => (
<PostWrapper
ref={posts.length === index + 1 ? setLoader : null}
key={`${post?.id}${index}`}
post={post}
/>
)
)}
const PostWrapper = forwardRef(({post}, ref) => (
<Grid
ref={ref}
container
justifyContent="center"
item
spacing={1}
mt={2}
xs={8}
>
<Post
post={post}
/>
</Grid>
))
Here's what I understood, and I'll try to answer this as per my understanding. You have an array/list of Posts, and each post has an array/list of comments. I am assuming it is nested and posts are embedded in the same "Posts" array.
When you update the Posts array, React re-renders/refreshes the page with the new changes. When you add an element at the start, all the elements are pushed one position to the right, triggering a refresh for each post. And, for the same reason, you don't see that when you append it at the last.
Two ways to avoid additional API Calls for existing Posts. Choose which one suits your use-case better:
// Approach 2
this.setState(state => ({
posts: [...state.posts, newPost]
}));