use-function-state
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

useFunctionState

npm package license

React's useState hook has special behavior if it is passed a function as initial or updated state. This can be convenient, but makes life hard if you actually just want to store a function in the state.

This hook allows you to easily store a function as React state. It is implemented via a simple useReducer call and has proper TypeScript definitions.

Example

import useFunctionState from 'use-function-state';
 
const initialFn = () => {};
const Comp = () => {
  const [fn, setFn] = useFunctionState(initialFn);
 
  return (
    <>
      {typeof fn /* 'function' (useState would have made this undefined) */}
      {setFn.length /* 1 (the newFn parameter of the setter) */}
    </>
  );
};

See example.test.tsx for a more realistic usage example.

Readme

Keywords

none

Package Sidebar

Install

npm i use-function-state

Weekly Downloads

1

Version

0.1.0

License

MIT

Unpacked Size

7.1 kB

Total Files

11

Last publish

Collaborators

  • jeysal