Etanor
Etanor

Reputation: 138

Performance issue - Only update the component that displays the data

I am running into a performance issue that I don't know how to solve. I have a component structure like so (<PostDetail> being the parent component):

Data structure

Data in the post state that is passed through the PostContext (see below)

{
    "_id": "5eb1a5dd53ec08cdabca7ef3",
    [... more data]
    "description": "{blocks: Array(5), entityMap: {…}}",
    "likeCount": 6,
    "comments": "[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]"
    isLikedByUser: true
}

On the following screen, you can see the chrome performance tab when I click on the "Like" button of my component, that updates the likeCount, which is only displayed in the <LikeCount> component.

Performance

When I click on the "Like" button, I send standard Axios post request and then, I update my post state that is passed through the PostContext using :

import { PostContext } from "../../../context/PostContext"
const [post, setPost] = useContext(PostContext)
[...]
setPost({ ...post, isLikedByUser: isLiked, likeCount: likeCount })

Nothing fancy here but, as you can see on the previous screenshot, the whole update takes about 300ms (it's even worse on a smartphone...), which is very bad for the user experience.

What can I do to only update the <LikeCount>, and not the other components inside <PostDetail> (<Description> or <Comments> for instance)

Upvotes: 1

Views: 109

Answers (1)

Prathap Reddy
Prathap Reddy

Reputation: 1739

Since increasing number of comments causing issues with like of posts

I would recommend you to wrap the Comments component with React.memo (equivalent to shouldComponentUpdate in class component) which block unnecessary re-rendering of Comments if there are no updates to it.

Note: React.memo only checks for prop changes. If your function component wrapped in React.memo has a useState or useContext Hook in its implementation, it will still rerender when state or context change.

Infact, you can wrap all such components which don't need unnecessary rendering.

Remember the below statement from docs

Even though React only updates the changed DOM nodes, re-rendering still takes some time. In many cases it’s not a problem, but if the slowdown is noticeable, you can speed all of this up by overriding the lifecycle function shouldComponentUpdate, which is triggered before the re-rendering process starts.

Upvotes: 1

Related Questions