Skip to content

Commit

Permalink
feat: 🎸 add createMemo hook factory
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Oct 29, 2018
1 parent 25f6ea9 commit 8730eaa
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
<br/>
<br/>
- [**State**](./docs/State.md)
- [`createMemo`](./docs/createMemo.md) &mdash; creates a memoized hook.
- [`useGetSet`](./docs/useGetSet.md) &mdash; returns state getter `get()` instead of raw state.
- [`useGetSetState`](./docs/useGetSetState.md) &mdash; as if [`useGetSet`](./docs/useGetSet.md) and [`useSetState`](./docs/useSetState.md) had a baby.
- [`useObservable`](./docs/useObservable.md) &mdash; tracks latest value of an `Observable`.
Expand Down
28 changes: 28 additions & 0 deletions docs/createMemo.md
Original file line number Diff line number Diff line change
@@ -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 (
<div>
fib(10) = {result}
</div>
);
};
```
28 changes: 28 additions & 0 deletions src/__stories__/createMemo.story.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div>
fib(10) = {result}
</div>
);
};

storiesOf('createMemo', module)
.add('Docs', () => <ShowDocs md={require('../../docs/createMemo.md')} />)
.add('Demo', () =>
<Demo/>
)
5 changes: 5 additions & 0 deletions src/createMemo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import {useMemo} from './react';

const createMemo = fn => (...args) => useMemo(() => fn(...args), args);

export default createMemo;
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import createMemo from './createMemo';
import useAsync from './useAsync';
import useAudio from './useAudio';
import useBattery from './useBattery';
Expand Down Expand Up @@ -38,6 +39,7 @@ import useUpdate from './useUpdate';
import useWindowSize from './useWindowSize';

export {
createMemo,
useAsync,
useAudio,
useBattery,
Expand Down

0 comments on commit 8730eaa

Please sign in to comment.