Render only updated items in an array

Whenever I update user (object) in users (array) in context – all components which uses users re-renders.


What I’ve tried

I’ve component which is using values from context:

const DashboardCardList=()=> {
    const context = useContext(StaticsContext);
    const users = context.users.filter(user=>user.visible);

    return !users
        ? <Loading/>
        : (
            <Container>
                {users.map(user=>
                    <DashboardCard key={user._id} user={user}/>
                )}
            </Container>
        );
};

My update function (updates context state):

const onUserUpdate=(user)=>{
   const index = this.state.users.findIndex(item => item._id === user._id);
   const users = [...this.state.users]
   users[index] = user;
   this.setState({users:users});
}

Final component:

const DashboardCard=({user})=> {
    console.log("I'm here!", user);
    return ...;
}

Question

Why it keeps re-rendering? Is it because of context?
How to write this properly?

58 thoughts on “Render only updated items in an array”