Skip to content

useMemoizedFn

Category
Export Size
200 B
Last Changed
4 days ago

Keep a function's identity stable while always calling its latest implementation.

Demo

Usage

tsx
import { 
useMemoizedFn
} from '@reause/shared'
const [
count
,
setCount
] =
useState
(0)
// no deps array: the identity never changes, the body always reads `count` const
show
=
useMemoizedFn
(() =>
console
.
log
(
count
))

Passing show to a memoised child keeps that child from re-rendering when count changes — the reason to reach for it over useCallback, whose identity follows its deps.

useLatest covers adjacent ground differently: it tracks a value and hands back a ref, while this hook hands back a stable callable. react-use's useEvent is the closest upstream equivalent of that callable form.

Type Declarations

ts
type PickFunction<T extends noop> = (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnType<T>

export function useMemoizedFn<T extends noop>(fn: T): PickFunction<T>

Source

Source · Demo

Contributors

hairyf

Changelog

v0.1.7 on
3fcb5 - feat(shared): add useMemoizedFn (#946)

Released under the MIT License. v0.1.8