Andaman
Andaman

Reputation: 387

How to optimize List rendering in Reactjs

I am working on one React.js Application where i need to show checkbox checked ,if user is already present in selected users. I am able to implement that logic ,but the problem is , i have to compare user with thousand of other users to check if user is already in selected users,as it makes my application very slow to compare with thousands of users . How can optimize this List rendering,

const isSelectedArea = (user) => {
    selectedUsers.forEach((u) => {
      if (u.find((a) => a._id === user._id)) {
         return true;
       }
      
    });
  };

<span className={`block border-gray-200 bg-gray-200 ${isSelectedUser(user) ? "check":" "}`}></span>

Upvotes: 0

Views: 86

Answers (1)

Tomas Vancoillie
Tomas Vancoillie

Reputation: 3868

You could work with state and an click event handler to save the selected user. Then a simple check to see if the current user id is equal to the selected user id is enough to add the extra css class.

const [selectedUserId, setSelectedUserId] = useState();

const onClick = (userId) => {
  setSelectedUserId(userId)
}

return <div className={`button ... ${selectedUserId === user.id ? 'check' : ''}} onClick={() => onClick(user.id)}>{user.whatever}</div>

Upvotes: 1

Related Questions