0.1.0 • Published 5 years ago

use-function-state v0.1.0

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

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.