Skip to content

Commit

Permalink
main 🧊 add use event demo
Browse files Browse the repository at this point in the history
  • Loading branch information
debabin committed Jun 2, 2024
1 parent 31057eb commit cba80a9
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/hooks/useEvent/useEvent.demo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React from 'react';

import { useCounter } from '../useCounter/useCounter';
import { useRenderCount } from '../useRenderCount/useRenderCount';

import { useEvent } from './useEvent';

interface MemoComponentProps {
onClick: () => void;
}

const MemoComponent = React.memo(({ onClick }: MemoComponentProps) => {
const rerenderCount = useRenderCount();

return (
<>
<p>
Memo component rerender count: <code>{rerenderCount}</code>
</p>
<button type='button' onClick={onClick}>
Send message
</button>
</>
);
});

const Demo = () => {
const counter = useCounter();

const onClick = useEvent(() => counter.inc());

return (
<>
<p>
Count is: <code>{counter.count}</code>
</p>
<MemoComponent onClick={onClick} />
</>
);
};

export default Demo;
12 changes: 12 additions & 0 deletions src/hooks/useEvent/useEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ import React from 'react';

import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect/useIsomorphicLayoutEffect';

/**
* @name useEvent
* @description - Hook that creates an event and returns a stable reference of it
*
* @template Params The type of the params
* @template Return The type of the return
* @param {(...args: Params) => Return} callback The callback function
* @returns {(...args: Params) => Return} The callback
*
* @example
* const onClick = useEvent(() => console.log('clicked'));
*/
export const useEvent = <Params extends unknown[], Return>(
callback: (...args: Params) => Return
): ((...args: Params) => Return) => {
Expand Down

0 comments on commit cba80a9

Please sign in to comment.