Keep components alive after unmount in solid.js

Overview

solid-keep-alive

npm GitHub Repo stars

Keep you components alive even after parent's unmounts, saving signals and DOM elements in cache to reuse them.

Demo

On StackBlitz: stackblitz.com/edit/solid-keep-alive-demo

Installation

With npm

npm install solid-keep-alive

With yarn

yarn add solid-keep-alive

Usage

Wrap components that you want to keep in cache in KeepAlive tags:

<KeepAlive id="unique-const-id">
  <Child1 />
  {/* ... */}
</KeepAlive>

But first, KeepAlive components need a context, so all of them MUST be a descendant of KeepAliveProvider. For this you have to wrap your app (preferably) in this provider.

import { render } from 'solid-js/web';
import App from './App';
import { KeepAliveProvider } from 'solid-keep-alive';

render(
  () => (
    <KeepAliveProvider>
      <App />
    </KeepAliveProvider>
  ),
  document.getElementById('root')
);

You can also put the provider anywhere in the tree, as long as all KeepAlive components are descendant of at least one. However you need to be cautious. Having multiple of these context providers in the same app is discouraged because of memory consumption.

Now you can use KeepAlive to cache parts of you application.

// ...
const [selected, setSelected] = createSignal('first');

return (
  <>
    <Switch>
      <Match when={selected() === 'first'}>
        <KeepAlive id="first-tab">
          {/* everything inside here is kept alive, even after Match unmounts */}
          <FirstView />
          <SomeOtherComponent />
        </KeepAlive>
      </Match>
      <Match when={selected() === 'second'}>
        <KeepAlive id="second-tab">
          {/* this too */}
          <SecondView />
        </KeepAlive>
      </Match>
      <Match when={selected() === 'third'}>
        {/* this is not kept alive, everything here is unmounted immediately */}
        <ThirdView />
      </Match>
    </Switch>
    {/* ... */}
  </>
);

In this example, when a Match unmounts, rather than unmounting children immediately, KeepAlive takes ownership of them and saves them in cache, so when Match is mounted again children don't need to be remounted, keeping the exact same signals and DOM elements.

Elements from cache are automatically remove when the maximum amount of elements is reached. Default is 10, but you can change this by passing a maxElements prop to the context provider:

<KeepAliveProvider maxElements={20}>
  <App />
</KeepAliveProvider>

To manually dispose elements from cache use the removeElement method from the useKeepAlive hook:

import { useKeepAlive } from 'solid-keep-alive';

const App = () => {
  const [elements, { removeElement }] = useKeepAlive();
  const clickHandler = () => {
    // manually remove cached element where id is 'home-view'
    removeElement('home-view');
  };
  // ...
};
You might also like...

Minimalistic configuration for TS to only extend JS with types. No TS features, no bundling. Readable maintainable code after compilation.

Minimalistic configuration for TS to only extend JS with types. No TS features, no bundling. Readable maintainable code after compilation.

ts-guideline Minimalistic configuration for TS to only extend JS with types. No TS-scpecific features, no bundling. Readable maintainable code after c

Dec 22, 2022

A to-do list app is a productivity tool designed to help users to create and maintain lists of tasks that they need to complete and it allows user to edit their tasks even after the task is saved. Built with CSS, HTML, and JAVASCRIPT.

Tumaini Maganiko 📗 Table of Contents 📗 Table of Contents 📖 To Do List PROJECT 🛠 Built With Tech Stack Key Features 🚀 Live Demo 💻 Getting Started

May 9, 2023

Generate meshes from signed distance functions and constructive solid geometry operations.

Generate meshes from signed distance functions and constructive solid geometry operations.

sdf-csg Generate meshes from signed distance functions and constructive solid geometry operations. This library is heavily based upon Inigo Quilez's 3

Oct 24, 2022

Solid.js library adding a services layer for global shared state.

Solid.js library adding a services layer for global shared state.

Solid Services Services are "global" objects useful for features that require shared state or persistent connections. Example uses of services might i

Dec 30, 2022

solid material ui port (ported from blazor port)

solid-material-ui solid material ui port (porting from blazor port) In preparation for solid hack Turbo Mono-repository is used for component package

Apr 30, 2022

Solid hooks for Firebase v9.

solid-firebase Solid hooks for Firebase. Quick start Install it: yarn add firebase solid-firebase Configure firebase app: import { render } from 'soli

Dec 23, 2022

[WIP] A solid directive for adding colorful shadows to images.

solid-cosha A solid directive for adding colorful shadows to images (based on cosha). Quick start Install it: yarn add solid-cosha Use it: import { co

Feb 3, 2022

Add cmd+k interface to your solid site

solid-ninja-keys Add cmd+k interface to your solid site. Built on top of ninja-keys. Quick start Install it: yarn add solid-ninja-keys Use it: import

Dec 19, 2022

A helper to use immer as Solid.js Signal to drive state

Solid Immer A helper to use immer as Solid.js Signal to drive state. Installation $ npm install solid-immer Usage Use createImmerSignal to create a im

Nov 22, 2022
Owner
Julian Soto
(Web) Software Developer.
Julian Soto
Displaying actual age in percentage with 9 signs after dot (floating number)

Actual Age Chrome Extension Displaying actual age in percentage with 9 signs after dot (floating number) Features Popup You can select your Birth date

Igor Makeenko 22 Nov 2, 2022
Run async code one after another by scheduling promises.

promise-scheduler Run async code in a synchronous order by scheduling promises, with the possibility to cancel pending or active tasks. Optimized for

Matthias 2 Dec 17, 2021
Save resources by suspending unused tabs after 20 min.

Tab Suspender [WIP] Save resources by suspending unused tabs after 20 min. Instalation Enable Epiphany extension. Optional if not done. Download the l

null 5 May 7, 2022
Rename image after pasting, support name pattern and auto renaming.

Obsidian paste image rename This plugin is inspired by Zettlr, Zettlr shows a prompt that allows the user to rename the image, this is a great help if

Xiao Meng 82 Jan 2, 2023
✏️ Super lightweight JSX syntax highlighter, around 1KB after minified and gzipped

Sugar High Introduction Super lightweight JSX syntax highlighter, around 1KB after minified and gzipped Usage npm install --save sugar-high import { h

Jiachi Liu 67 Dec 8, 2022
My terrible attempt at a promposal. Update: She said yes LMFAO Update Update: I got friendzoned right after 😭

TypeScript Next.js example This is a really simple project that shows the usage of Next.js with TypeScript. Deploy your own Deploy the example using V

John Li (Tet) 7 Oct 27, 2022
This is a website for you to write what you want to do after or done befor and manage it.

Todo List Website This is a website for you to write what you want to do after or done befor and manage it. LogIn SignUp Main Abilities Able To Run Se

Alireza 6 Dec 21, 2022
Change import URLs in JavaScript code using import maps. e.g. `import * from "before"` to `import * from "after"`

esm-import-transformer Can transform any ESM source code import URLs using an import maps object. This package works in ES modules or in CJS. // Befor

Zach Leatherman 19 Jul 31, 2022
This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way, this plugin works after page load.

Jquery-SingleImagePopup This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way

Rajan Karmaker 1 Aug 22, 2022
Fork of DevilBro's ShowHiddenChannels plugin for BetterDiscord, works after guideline change.

DefinitelyNotSHC BetterDiscord has set into effect some new plugin guidelines that block plugins like ShowHiddenChannels from being distributed on the

null 54 Dec 21, 2022