'Animate component unmount fade-out in React Native

On a React Native application, given a condition is true I should render ComponentA, else ComponentB should be visible instead.

const ParentComponent = () => {
  if (condition) return <ComponentA />
  if (!condition) return <ComponentB />
}

The issue I have is that once the condition changes I should animate the transition between the components, i.e., ComponentA should fade out and ComponentB should fade in.

So in ComponentA I have something like this:

useEffect(() => {
  return () => {
    Animated.timing(fadeAnim, {
        useNativeDriver: true,
        toValue: 0,
        duration: 1000,
      }).start();
    })
  }
}

Meaning that when the component is about to unmount it should trigger the fade-out animation. This does not work however because by the time the animation should start the component has already disappeared, since the condition that allows its rendering has already changed and the other component is now rendered instead (see first code snippet).

Is there a way to animate the component's unmounting without any extra libraries?

As a workaround I am rendering both components and changing their opacity: I pass the condition to both of them as a prop, so that when the condition changes they can handle the animation for opacity change themselves, but I don't like this solution, since I have to make both components' position absolute and have them overlap on top of each other, ideally I would like to keep the condition that manages their rendering and have ComponentA unmount with a fade-out. Is that possible?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source