useRegisterNodeRef
A React hook that helps you to run some code when a DOM node mounts/dismounts.
npm i @utilityjs/use-register-node-ref | yarn add @utilityjs/use-register-node-ref
Keep in mind that useRef
doesn't notify you when its content changes. Mutating the current
property doesn't cause a re-render. This hook will register a callback to DOM node so you can be notified when it mounts/dismounts.
This hook also supports dynamic/conditional rendering as well.
Usage
const App: React.FC = () => {
const [isVisible, setVisibile] = React.useState(false);
const registerRef = useRegisterNodeRef(node => {
// The callback effect to invoke when node mounts/dismounts
const listener = () => {
console.log("clicked");
};
if (node) node.addEventListener("click", listener);
// The cleanup function
return () => {
if (node) node.removeEventListener("click", listener);
};
});
return (
<div className="app">
<button onClick={() => void setVisibile(v => !v)}>toggle</button>
{isVisible && <div ref={registerRef}>This is the DIV!</div>}
</div>
);
};
API
useRegisterNodeRef(callback, deps?)
declare type Destructor = () => void | undefined;
declare type Callback = <T extends HTMLElement>(
node: T | null
) => void | Destructor;
declare const useRegisterNodeRef: (
callback: Callback,
deps?: React.DependencyList
) => <T extends HTMLElement>(node: T | null) => void;
callback
The callback effect to invoke when DOM node mounts/dismounts.
Note: This callback can also return a cleanup function.
deps
- (default: []
)
If present, the callback will only be updated if the values in the list change.