Skip to content

Commit

Permalink
Recreate useUpdate after calls
Browse files Browse the repository at this point in the history
  • Loading branch information
littensy committed Apr 22, 2023
1 parent efad2bf commit 4f9e588
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
6 changes: 6 additions & 0 deletions src/use-update/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ function useUpdate(): () => void;

Returns a function that can be called to force an update of the component.

The function returned by `useUpdate` is recreated when it causes an update, making it useful to track re-renders caused by this hook.

### 📕 Parameters

### 📗 Returns
Expand All @@ -24,6 +26,10 @@ export default function Component() {
}, 1);
}, []);

useEffect(() => {
print("Rendered because of useUpdate");
}, [update]);

print("Rendered");

return <frame />;
Expand Down
15 changes: 15 additions & 0 deletions src/use-update/use-update.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,19 @@ export = () => {

expect(renders).to.equal(2);
});

it("should return a new function on each update", () => {
let rerender = () => {};
let previousRerender = () => {};

renderHook(() => {
previousRerender = rerender;
rerender = useUpdate();
});

expect(rerender).never.to.equal(previousRerender);

rerender();
expect(rerender).never.to.equal(previousRerender);
});
};
8 changes: 5 additions & 3 deletions src/use-update/use-update.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { useCallback, useState } from "@rbxts/roact-hooked";

/**
* Returns a function that can be used to force a component to update.
* Returns a function that can be used to force a component to update. The
* function is recreated on the next render if called. This makes it useful as
* a dependency for other hooks.
* @returns A function that forces a rerender.
*/
export function useUpdate() {
const [, setState] = useState({});
const [state, setState] = useState({});

return useCallback(() => {
setState({});
}, []);
}, [state]);
}

0 comments on commit 4f9e588

Please sign in to comment.