Skip to content

createBackStack

Creates a back stack: a stack that always has a current entry (the one on top), with the previous ones underneath to go back to. The bottom entry is never removed, so there is always something to show: screens of a prototype, overlays stacked over a screen (with null as the initial entry), wizard steps, undo levels.

It does not decide what the next entry is: compute it (with a state machine, a router, …) and push it.

Available since v3.1.5

import { createBackStack } from '@helpers4/structure';
// or, from the all-in-one package (same code, one install):
import { createBackStack } from 'helpers4/structure';
createBackStack<T>(initial: T, options: BackStackOptions): BackStack<T>
ParameterTypeDescription
initialTThe first current entry, also the default of BackStack.reset
optionsBackStackOptionsDepth limit — see BackStackOptions

BackStack<T> — A BackStack

push() moves to a new entry; back() returns the entry it left and restores the previous one.

const screens = createBackStack('home');
screens.push('settings');
screens.back();  // => 'settings'
screens.current; // => 'home'

Change the current entry without a step to undo

Section titled “Change the current entry without a step to undo”

replace() swaps the current entry and keeps the ones underneath; previous is where back() would go.

const screens = createBackStack('home');
screens.push('menu');
screens.replace('menu-closed');
screens.previous; // => 'home'
screens.back();   // => 'menu-closed'

limit caps how many past entries are kept; the oldest are dropped first.

const stack = createBackStack('', { limit: 1 });
stack.push('a');
stack.push('ab');
stack.back(); // => 'ab'
stack.back(); // => undefined — '' was dropped

A back stack created by createBackStack.

interface BackStack<T> {
  canGoBack: boolean;
  current: T;
  previous: T | undefined;
  back(): T | undefined;
  push(value: T): void;
  replace(value: T): void;
  reset(value?: T): void;
  subscribe(listener: function): function;
}

Options for createBackStack.

interface BackStackOptions {
  limit?: number;
}

View source on GitHub