Delay unmounting of the component in React

When you want to trigger animations before the component will disappear from your page you need to postpone unmounting of the component.

It is fairly easy to animate a mounting component. You can just write CSS class with @keyframes rule and attach this CSS class to HTML element. That’s it. When the component mounts with appropriate styles it triggers the keyframes animation. But what if you want to trigger the animation when the component is going to unmount? You need to somehow delay unmounting of the component, so the animations will have time to end before the component will disappear from the document.

But how can you do this? The idea is very simple!

As you can see, I’ve created HOC that handles all the logic responsible for it. If the component wants to unmount, I am delaying it by setting the state in setTimeout. If the component wants to mount, I am just rendering it — without any delay. And that’s all!

A higher-order component (HOC) is a function that takes a component and returns a new component.

Now you can use this HOC like this:

And this is how it looks in action:

🎉 We did it! 🎉 Click here to see the code.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.