Like useRef, but with lifecycle and ref merging support
Here is a simplfied demonstration on how easy to use useLifecycleRef
.
import React, { type ForwardedRef, type Ref, forwardRef } from 'react';
import useLifecycleRef from 'use-lifecycle-ref';
export function ComponentHidingRef({ id }: { id: string }) {
const ref = useLifecycleRef<HTMLDivElement>({
onAttach: (el: HTMLDivElement) => {
console.log(`${el} attached`);
},
onDetach: (el: HTMLDivElement) => {
console.log(`${el} detached`);
}
});
return <div id={id} ref={ref}>Hello World</div>;
};
export const ComponentExposingRef = forwardRef(function HelloWorld(
{ id }: { id: string },
ref: ForwardedRef<HTMLDivElement>
) {
const _ref = useLifecycleRef<HTMLDivElement>({
onAttach: (el: HTMLDivElement) => {
console.log(`${el} attached`);
},
onDetach: (el: HTMLDivElement) => {
console.log(`${el} detached`);
},
ref
});
return <div id={id} ref={_ref}>Hello World</div>;
});
This library has been continuously used in many of my personal projects, and is regarded as production-ready. In the foreseeable future, I will continuously maintain and support this library.
Please voice your opinion and report bugs in the issues sections of this GitHub project.
You are more than welcome to add more functionalities, improve documentation, fix bugs, and anything you think is needed. The build step is pretty self-explanatory. Please refer to package.json
.
MIT