Is it better to unmount a component or hide it with CSS?

Viewed 866

enter image description here I have a header component in my React Native application that slides out of the screen when the users keyboard opens. This is so that I can create more space. When the animation is complete, I can either unmount the component (using Redux with its parent component) or hide it by applying flex: 0.

Which method is better? or is there no difference?

2 Answers

There are two things to consider:

  • do you need data to persist between hiding/showing the header?
  • do you need the header to be read by a screen reader when it is hidden?

If the header contains any state that needs to persist, hiding the element with css is preferred over unmounting. As an example, imagine your header has a count that starts at 0 and counts up each second the user is on the page. If you unmount the header when it disappears, the count will restart at 0. If you hide the element with css, the count will persist when it reappears.

If the header needs to be read by a screen reader while hidden by the keyboard, be sure to hide it with css. The screen should still pick up the elements while hidden, but unmounted they will not be visible because the elements will be effectively removed from the page.

If these are not concerns in your project, then either option should be fine.

If you want to use the animation, it's better height: 0

or use condition

this.state = {
  displayHeader : true
}

{this.state.displayHeader ? <YourTag >....</YourTag> : null}
Related