usePerformAction
Hook that executes a callback after a render.
Demo
INFO
The component load bootstrap script with useScript hook to use Bootstrap Dropdown, and renders two child components that render a Select and a Dropdown components. Every child component when select value is 2, executes a click on dropdown to open it by a ref attached on dropdown button.
The Child1 executes click on button but dropdown isn't displayed. The Child2 executes click with usePerformAction hook and shows the dropdown.
Loading demo…
Show source code
tsx
import { useRef } from "react";
import { usePerformAction } from "../../../../hooks/events/usePerformAction";
import { useScript } from "../../../../hooks/api-dom/useScript"
import { Dropdown } from "./Dropdown";
import { Select } from "./Select";
const Child1 = () => {
const ref = useRef<HTMLButtonElement>(null);
const perform = (() => ref.current?.click());
return (<div>
<p><strong>
Component without performAction
</strong></p>
<Select action={perform}/>
<br />
<br />
<Dropdown btnRef={ref}/>
</div>);
}
const Child2 = () => {
const ref = useRef<HTMLButtonElement>(null);
const perform = usePerformAction(() => ref.current?.click());
return (<div>
<p><strong>
Component with performAction
</strong></p>
<Select action={perform} />
<br />
<br />
<Dropdown btnRef={ref} />
</div>);
}
const UsePerformAction = () => {
const [status] = useScript(
{
src: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js",
integrity:"sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL",
crossorigin: "anonymous"
},
{
removeOnUnmount: true
}
);
if (status === "loading") {
return null;
}
return (
<div style={{ display: "grid", gridTemplateColumns: "auto auto", justifyContent: "center", gap: 50 }}>
<Child1 />
<Child2 />
</div>
);
}
UsePerformAction.displayName = "UsePerformAction";
export { UsePerformAction };Types
UsePerformActionProps
@templateT - The type of the callback function. Must extend a function accepting any number of unknown arguments and returning void.
Parameters accepted by usePerformAction.
| Property | Type | Required | Description |
|---|---|---|---|
cb | T | ✓ | The function to wrap. Its parameter types are preserved on the returned stable callback via Parameters<T>, ensuring type safety at call sites. |
UsePerformActionResult
@templateT - The type of the original callback function.
Return value of usePerformAction.
A stable memoized function with the same parameter signature as cb. Calling it always invokes the latest version of cb without the wrapped function identity changing between renders.
ts
export type UsePerformActionResult<T extends (...args: unknown[]) => void> =
(...args: Parameters<T>) => void;