createPreviousMemo (SolidJS)

Get an accessor for the previous value of the provided signal. Returns undefined when the provided signal hasn't changed yet.

typescriptjavascript
export const createPreviousMemo = <T>(
  get: Accessor<T>
): Accessor<T | undefined> => {
  let currValue: T | undefined = undefined
  const [prev, setPrev] = createSignal<T | undefined>()
  createEffect(() => {
    const nextValue = currValue
    setPrev(() => nextValue)
    currValue = get()
  })
  return prev
}
export const createPreviousMemo = get => {
  let currValue = undefined
  const [prev, setPrev] = createSignal()
  createEffect(() => {
    const nextValue = currValue
    setPrev(() => nextValue)
    currValue = get()
  })
  return prev
}

Usage

typescriptjavascript
import { type VoidComponent, createSignal } from 'solid-js'
 
const Example = () => {
  const [count, setCount] = createSignal(0)
  // Note - we're passing in an accessor / getter function and not the value
  const previousCount = createPreviousMemo(count)
 
  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <p>Current count: {count()}</p>
      <p>Previous count: {previousCount().toString()}</p>
    </>
  )
}
import { createSignal } from 'solid-js'
 
const Example = () => {
  const [count, setCount] = createSignal(0)
  // Note - we're passing in an accessor / getter function and not the value
  const previousCount = createPreviousMemo(count)
 
  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <p>Current count: {count()}</p>
      <p>Previous count: {previousCount().toString()}</p>
    </>
  )
}

Demo

Created 01/01/23Updated 20/06/23
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here