Skip to content

Commit

Permalink
Create useLatest
Browse files Browse the repository at this point in the history
  • Loading branch information
littensy committed Apr 22, 2023
1 parent 3eb6496 commit 82f61ea
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/use-latest/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
## 🪝 `useLatest`

```ts
function useLatest<T>(value: T): { current: T };
```

Returns a ref object whose `current` property always points to the latest version of the value.

### 📕 Parameters

- `value` - The value to wrap in a ref.

### 📗 Returns

- A ref object.

### 📘 Example

```tsx
export default function Component() {
const [value, setValue] = useState(0);
const latestValue = useLatest(value);

useEffect(() => {
const connection = RunService.Heartbeat.Connect(() => {
print(latestValue.current);
});

return () => {
connection.Disconnect();
};
}, []);

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

import { renderHook } from "../utils/testez";
import { useLatest } from "./use-latest";

export = () => {
it("should return a mutable ref", () => {
const { result } = renderHook(() => useLatest(0));
expect(result.current.current).to.equal(0);
});

it("should update the ref when the value changes", () => {
const { result, rerender } = renderHook((props: { value: number }) => useLatest(props.value), {
initialProps: { value: 0 },
});

expect(result.current.current).to.equal(0);
rerender({ value: 1 });
expect(result.current.current).to.equal(1);
});
};
12 changes: 12 additions & 0 deletions src/use-latest/use-latest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useMutable } from "@rbxts/roact-hooked";

/**
* Returns a mutable ref that always points to the latest value of the input.
* @param value The value to track.
* @returns A mutable reference to the value.
*/
export function useLatest<T>(value: T) {
const ref = useMutable(value);
ref.current = value;
return ref;
}

0 comments on commit 82f61ea

Please sign in to comment.