react-use-stable
TypeScript icon, indicating that this package has built-in type declarations

0.2.2 • Public • Published

use-stable

React hook meant to create a stable value that only clears when the dependencies change.

This is different from useMemo, which is a memoized value, that can be recreated even when dependencies don't change:

However, since useMemo is performance optimization, not a semantic guarantee, React may throw away the cached value if there is a specific reason to do that.

This hook is meant for cases that are not pure, usually when the return is a pointer that is meaningful -- for WeakMap, WeakSet, and other associative data structures.

API is the same as useMemo.

import useStable from 'react-use-stable'

function useMyCustomHook(socket) {
    const socket = useStable(()=>new WebSocket(`wss://example.com/${socket}`), [socket]);

    // use socket as a prop for other components/hooks
}

/react-use-stable/

    Package Sidebar

    Install

    npm i react-use-stable

    Weekly Downloads

    17

    Version

    0.2.2

    License

    ISC

    Unpacked Size

    5.17 kB

    Total Files

    8

    Last publish

    Collaborators

    • vikr01