Home > Net >  React functional component is not re-rendering on state change
React functional component is not re-rendering on state change

Time:04-16

const addComment = (c:IComment) => {
    if(post){
        var p = post // creating a copy of my post state
        p.comments = [c, ...p.comments] // creating new comments array with the new comment and all old ones
        setPost(p) // setting post state to be newly updated post
        console.log(post) // console log confirms state has in fact been changed and the new comment is there
        // component has not re rendered....
    }`
}

sorry, the code formatting option here doesn't seem to be working. But this is basically the issue, changing my state works fine, but the component just refuses to re-render when its state changes.

CodePudding user response:

The problem is the way you cloned the post. A deep copy of the post is required to resolve this issue.

1- Using the spread operator

const addComment = (c:IComment) => {
    if(post){
        const p = {...post}
        p.comments = [c, ...p.comments]
        setPost(p)
    }
}

2- Using JSON

const addComment = (c:IComment) => {
    if(post){
        const p = JSON.parse(JSON.stringify(post))
        p.comments = [c, ...p.comments]
        setPost(p)
    }
}

  • Related