Skip to content

Commit

Permalink
Create useUnmount
Browse files Browse the repository at this point in the history
  • Loading branch information
littensy committed Apr 22, 2023
1 parent 7c848bb commit d56916e
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/use-unmount/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
## 🪝 useUnmount

```ts
function useUnmount(callback: () => void): void;
```

Calls the callback when the component unmounts. This is useful for cleaning up side effects.

### 📕 Parameters

- `callback` - The callback to call when the component unmounts.

### 📗 Returns

- `void`

### 📘 Example

```tsx
export default function Component() {
useUnmount(() => {
print("Unmounting...");
});

return <frame />;
}
```
1 change: 1 addition & 0 deletions src/use-unmount/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./use-unmount";
32 changes: 32 additions & 0 deletions src/use-unmount/use-unmount.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/// <reference types="@rbxts/testez/globals" />

import { renderHook } from "../utils/testez";
import { useUnmount } from "./use-unmount";

export = () => {
it("should call when component unmounts", () => {
let called = false;
const { unmount } = renderHook(() => useUnmount(() => (called = true)));
expect(called).to.equal(false);
unmount();
expect(called).to.equal(true);
});

it("should not call on rerender", () => {
let called = false;
const { rerender } = renderHook(() => useUnmount(() => (called = true)));
expect(called).to.equal(false);
rerender();
expect(called).to.equal(false);
});

it("should call the last callback on unmount", () => {
let called = 0;
const { rerender, unmount } = renderHook((callback: () => void) => useUnmount(callback), {
initialProps: () => (called = 0),
});
rerender(() => (called += 1));
unmount();
expect(called).to.equal(1);
});
};
16 changes: 16 additions & 0 deletions src/use-unmount/use-unmount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useEffect } from "@rbxts/roact-hooked";
import { useLatest } from "../use-latest";

/**
* Calls the callback when the component unmounts.
* @param callback The callback to call.
*/
export function useUnmount(callback: () => void) {
const callbackRef = useLatest(callback);

useEffect(() => {
return () => {
callbackRef.current();
};
}, []);
}

0 comments on commit d56916e

Please sign in to comment.