Home > database >  React don't mount component until needed but don't unmount afterwards in list of component
React don't mount component until needed but don't unmount afterwards in list of component

Time:11-28

Say I am building an instant messaging with app with React (I'm not doing that exactly, but this is easier to explain). I have a sidebar with a list of conversations and, when you click one, it is shown on the right (similar to this). I don't want to mount each conversation component until the user clicks it, but I don't want to unmount it, just hide it, when they click on another conversation. How can I do this cleanly? There will never be more than about 30 chats for any user.

CodePudding user response:

You can store the enabled conversations in an array that you use to show, and when you disable a conversation you can just add a hidden prop to it which you pass to the conversation and make it return null. This will make it not render anything but will not unmount it since you have not removed it from the array that handles the display of conversations.

example at: https://codesandbox.io/s/wispy-forest-59bqj

CodePudding user response:

This is a bit hard to answer since you haven't posted the code.

But, theoretically, the best way to approach this problem is to transfer the data from your sidebar component and load it onto the right component on a per-user basis. You don't have to mount each "conversation component".

  • Related