npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@anion155/react-hooks

v0.2.3

Published

React utility hooks

Downloads

45

Readme

React Hooks and utilities library

This library contains utilities and react hooks.

API hooks

import {} from '@anion155/react-hooks';

useConst

function useConst<T>(fabric: () => T): T;

Creates value on the first render, at render time.

const store = useConst(() => createStore());

useRenderEffect

type EffectCallback = () => (void | (() => void));
function useRenderEffect(effect: EffectCallback, deps: DependencyList): void;

Effect hook that runs at render time.

const ref = useRef(value);
useRenderEffect(() => {
  ref.current = value;
}, [value]);
// ref.current === value

Note

It is not guaranteed that cleanup function would be run during render. Specifically last cleanup before unmount is running as useEffect cleanup function.

useSetStateDispatcher

type SetStateDispatcher<T> = (state: T | ((current: T) => T)) => void;
function useSetStateDispatcher(get: () => T, set: (value: T) => void): SetStateDispatcher<T>;

Creates stable set state action dispatcher function, which accepts next value or modifier.

const store = {
  current: null,
  get() { return this.current; },
  set(next) { this.current = next },
};
const dispatcher = useSetStateDispatcher(
  () => store.get(),
  (next) => store.set(next),
);
dispatcher(10);
dispatcher(current => current * 2);

useEventState

function useEventState<T>(stateInitial: StateInitial<T>): [T, (arg: T) => void];
function useEventState<As extends unknown[], T>(
  stateInitial: StateInitial<T>,
  project: (...args: As) => T,
  deps: DependencyList
): [T, (...args: As) => void];

Creates event handler that stores event value in state.

const [value, handleChange] = useEventState('', (event) => event.target.value);
<>
  <input onChange={handleChange} />
  <span>Value: "{value}"</span>
</>

useStableCallback

function useStableCallback<F>(
  cb: (...args: Parameters<F>) => ReturnType<F>
): (...args: Parameters<F>) => ReturnType<F>;

Creates stable callback instance, result function never changes until unmounted.

const [counter, setCounter] = useState(1);
const cb = useStableCallback(() => {
  setCounter(counter + 1);
});
useEffect(() => {
  console.log('Runs one time only');
}, [cb]);
<button onClick={cb} />

useFabric

function useFabric<T>(fabric: () => T, deps: DependencyList): T;

Creates value every time deps are changed.

Note

This is fully controlled version of useMemo, that will not follow useMemo cache policies. See useMemo caveats

const controller = useFabric(() => new ControllerClass(value), [value]);

useInputState

function useInputState<T extends {}>(props: {
  value: T;
  defaultValue?: T;
  onValueChange: (value: T) => void;
}): [T, SetStateDispatcher<T>];
function useInputState<T extends {}>(props: {
  value?: T;
  defaultValue: T;
  onValueChange?: (value: T) => void;
}): [T, SetStateDispatcher<T>];

Creates tuple of value and set state acton dispatcher based on commonly used set of props value, onValueChange and defaultValue. Allows to create input components capable of being used as controlled component and as uncontrolled.

function CustomInput(props) {
  const [value, setValue] = useInputState(props);
  return <input value={value} onChange={e => setValue(e.value)} />
}
// uncontrolled version
<CustomInput defaultValue={5} />
// or as controlled input
const [value, setValue] = useState(5);
<CustomInput value={value} onValueChange={(e) => setValue(e.value)} />

useLensedState

function useLensedState<T, U>(
  sourceState: readonly [T, SetStateDispatcher<T>],
  getter: (state: T) => U,
  setter: (value: U, state: T) => T
): [U, SetStateDispatcher<U>];

Creates state tuple binded to source state.

const formState = useState({ name: '', password: '' });
<Context.Provider value={formState}> />
const [name, setName] = useLensedState(
  useContext(Context),
  form => form.name,
  (name, form) => ({ ...form, name })
);
setName(current => 'mr.' + current);

API utils

There is submodule with utility functions

import {} from '@anion155/react-hooks/utils';

hasOwnProperty

function hasOwnProperty<P extends string, T>(obj: unknown, propertyName: P): obj is { [p in P]: T };

Type safe check if object has own property.

if (hasOwnProperty(obj, 'field')) {
  obj.field; // ts now knows that obj has property 'field' of unknown type
}

assert

function assert(condition: unknown, message?: string): asserts condition;

Simple assert function.

assert(hasOwnProperty(obj, 'field'), 'obj does not have property named "field"');
obj.field; // ts now knows that obj has property 'field' of unknown type

warning

function warning(condition: unknown, message?: string): void;

Output warning message to console, falsy condition can be used as a debugger breakpoint if 'pause on all exceptions' enabled in debugger. Does not assert value.

warning(hasOwnProperty(obj, 'field'), 'obj does not have property named "field"');
obj?.field; // ts now knows that obj has property 'field' of unknown type

cancelablePromise

class CanceledError extends Error;
type CancelablePromise<T> = Promise<T> & { cancel: () => void };
type CancelState = { canceled: boolean };
type CancelablePromiseExecutor<T> = (
  resolve: (value: T | PromiseLike<T>) => void,
  reject: (reason?: unknown) => void,
  state: Readonly<CancelState>
) => void | { (): void };
function cancelablePromise<T>(executor: CancelablePromiseExecutor<T>): CancelablePromise<T>;

Creates cancelable promise.

const promise = cancelablePromise((resolve, reject, state) => {
  const controller = new AbortController();
  fetch('/something', { signal: controller.signal });
  setTimeout(() => {
    if (!state.canceled) return;
    reject(new Error('Timeout'));
  }, 1000);
  return () => {
    controller.abort();
  };
});
promise.cancel();

asyncDelay

function asyncDelay(timeout: number): CancelablePromise<void>;

Creates cancelable promise that will be resolved with timeout passed.

await asyncDelay(1000);

compareProps

function compareProps(prev: DependencyList, next: DependencyList): boolean;

Compares two dependencies arrays, return true if they are equal.

compareProps(["same", 1], ["same", 2]) === 2;

useRenderDispatcher

function useRenderDispatcher<S>(
  deps: DependencyList,
  onChange: (state: S | undefined, prevDeps: DependencyList | undefined) => S
): S;

Creates cross render state based on deps.

const useMemo = (creator, deps) => useRenderDispatcher(deps, creator);