Skip to content

Commit 245fe20

Browse files
committed
feat(react-components): add useMount hook with documentation and stories
1 parent 332f72e commit 245fe20

File tree

4 files changed

+83
-0
lines changed

4 files changed

+83
-0
lines changed

packages/react-components/src/hooks/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@ export { useEventCallback } from './use_event_callback';
2020
export { useEnhancedEffect } from './use_enhanced_effect';
2121
export { useDebounceCallback } from './use_debounce_callback';
2222
export { useOutsideClick } from './use_outside_click';
23+
export { useMount } from './use_mount';
2324
export { createDialog } from './create_dialog';
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { Meta, Canvas } from '@storybook/blocks';
2+
import * as Stories from './use_mount.stories';
3+
4+
<Meta title="Hooks/useMount" />
5+
6+
## Overview
7+
8+
React hook that runs a callback only once when the component mounts.
9+
10+
## Usage
11+
12+
```jsx
13+
import { useMount } from '@peculiar/react-components';
14+
15+
function Child() {
16+
useMount(() => {
17+
alert('I have been mounted');
18+
});
19+
20+
return <div></div>;
21+
}
22+
23+
export const Demo = () => {
24+
const [mounted, setMounted] = useState(false);
25+
26+
return (
27+
<div>
28+
<button onClick={() => setMounted((b) => !b)}>
29+
{mounted ? 'Mounted' : 'UnMounted'}
30+
</button>
31+
32+
{mounted ? <Child /> : null}
33+
</div>
34+
);
35+
};
36+
```
37+
38+
## Demo
39+
40+
<Canvas of={Stories.DemoExample} />
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { useState } from 'react';
2+
import { useMount } from './use_mount';
3+
4+
const meta = {
5+
title: 'Hooks/useMount',
6+
component: useMount,
7+
};
8+
9+
export default meta;
10+
11+
function Child() {
12+
useMount(() => {
13+
alert('I have been mounted');
14+
});
15+
16+
return <div></div>;
17+
}
18+
19+
export const DemoExample = () => {
20+
const [mounted, setMounted] = useState(false);
21+
22+
return (
23+
<div>
24+
<button
25+
type="button"
26+
onClick={() => setMounted((b) => !b)}
27+
>
28+
{mounted ? 'Mounted' : 'UnMounted'}
29+
</button>
30+
{mounted ? <Child /> : null}
31+
</div>
32+
);
33+
};
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { useEnhancedEffect } from './use_enhanced_effect';
2+
3+
/**
4+
* React hook that runs a callback only once when the component mounts.
5+
* @param callback The callback function to run on mount.
6+
*/
7+
export function useMount(callback: () => void) {
8+
useEnhancedEffect(callback, []);
9+
}

0 commit comments

Comments
 (0)