Skip to content

useMemoizedFn

Stable callback reference that still sees fresh state.

Stable callback reference that still sees fresh state.

Import

import { useMemoizedFn } from '@kamod-ch/hooks'

Live demo

Basic demo

Stable callback reference that still sees fresh state.

Count: 0

import { useState } from 'preact/hooks'
import { useMemoizedFn } from '@kamod-ch/hooks'

export default function UseMemoizedFnDemo() {
  const [count, setCount] = useState(0)
  const increment = useMemoizedFn(() => setCount((value) => value + 1))

  return (
    <div>
      <p><strong>Count:</strong> {count}</p>
      <button type="button" onClick={increment}>Increment with stable callback</button>
    </div>
  )
}

API

TypeScript signature
type noop = (this: any, ...args: any[]) => any;
type PickFunction<T extends noop> = (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnType<T>;
declare const useMemoizedFn: <T extends noop>(fn: T) => PickFunction<T>;
export default useMemoizedFn;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.