Learn how to cache component instances in Vue.

Every time a component is rendered or mounted, Vue creates a new instance of this component. In most cases, we want this behavior—there’s no need to cache titles, static text, or entire pages of static content. Doing so would mean that Vue stores them in memory, even though they’re not in use. Sometimes though, cached components are helpful. They keep their state and need minimal setup time to be remounted by Vue. We can cache components by using <keep-alive>.

What does <keep-alive> do?

Vue tends to remove any unused components from memory by default. The more that is happening on a page, the more components Vue needs to render. To keep performance optimal, Vue tries to keep the memory footprint minimal. The main drawback is that a switch between components through, for example, routing, requires the component to be completely setup all over again. This setup results in slightly longer rendering times.

We can work around this mechanism by using <keep-alive>, which caches the component instance internally. When the component becomes necessary again, its VNode is remounted where it was located. It’s removed from the cache of <keep-alive> and marked as being kept alive again, restoring the original state before the unmount.

The internal cache is updated if a component does not count as being kept alive anymore (using include and exclude), so Vue is optimizing its memory usage even in this case. How <keep-alive> works is by using a default slot. We can add as many components as possible.

Let’s investigate the caching behavior regarding a component’s state. The SPA below has a component switcher implemented with two different components. Keep them alive using <keep-alive> and implement a state with a <textarea> or something similar.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy