diff --git a/README.md b/README.md index 0358f31630..5f7272f929 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@

- [**State**](./docs/State.md) + - [`createMemo`](./docs/createMemo.md) — creates a memoized hook. - [`useGetSet`](./docs/useGetSet.md) — returns state getter `get()` instead of raw state. - [`useGetSetState`](./docs/useGetSetState.md) — as if [`useGetSet`](./docs/useGetSet.md) and [`useSetState`](./docs/useSetState.md) had a baby. - [`useObservable`](./docs/useObservable.md) — tracks latest value of an `Observable`. diff --git a/docs/createMemo.md b/docs/createMemo.md new file mode 100644 index 0000000000..0fc5c1f0ab --- /dev/null +++ b/docs/createMemo.md @@ -0,0 +1,28 @@ +# `createMemo` + +A factory that returns a React hook, which is memoized for each set of arguments passed to it. + + +## Usage + +```jsx +import {createMemo} from 'react-use'; + +const fibonacci = n => { + if (n === 0) return 1; + if (n === 1) return 2; + return fibonacci(n - 1) + fibonacci(n - 2); +}; + +const useMemoFibonacci = createMemo(fibonacci); + +const Demo = () => { + const result = useMemoFibonacci(10); + + return ( +
+ fib(10) = {result} +
+ ); +}; +``` diff --git a/src/__stories__/createMemo.story.tsx b/src/__stories__/createMemo.story.tsx new file mode 100644 index 0000000000..9a07ddb2f6 --- /dev/null +++ b/src/__stories__/createMemo.story.tsx @@ -0,0 +1,28 @@ +import * as React from 'react'; +import {storiesOf} from '@storybook/react'; +import {createMemo} from '..'; +import ShowDocs from '../util/ShowDocs'; + +const fibonacci = n => { + if (n === 0) return 1; + if (n === 1) return 2; + return fibonacci(n - 1) + fibonacci(n - 2); +}; + +const useMemoFibonacci = createMemo(fibonacci); + +const Demo = () => { + const result = useMemoFibonacci(10); + + return ( +
+ fib(10) = {result} +
+ ); +}; + +storiesOf('createMemo', module) + .add('Docs', () => ) + .add('Demo', () => + + ) diff --git a/src/createMemo.ts b/src/createMemo.ts new file mode 100644 index 0000000000..59405a81a9 --- /dev/null +++ b/src/createMemo.ts @@ -0,0 +1,5 @@ +import {useMemo} from './react'; + +const createMemo = fn => (...args) => useMemo(() => fn(...args), args); + +export default createMemo; diff --git a/src/index.ts b/src/index.ts index b57e7a86f8..679c0d3477 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,4 @@ +import createMemo from './createMemo'; import useAsync from './useAsync'; import useAudio from './useAudio'; import useBattery from './useBattery'; @@ -38,6 +39,7 @@ import useUpdate from './useUpdate'; import useWindowSize from './useWindowSize'; export { + createMemo, useAsync, useAudio, useBattery,