use-lifecycle-ref

Like useRef, but with lifecycle and ref merging support

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
use-lifecycle-ref
1.0.68 months ago10 months agoMinified + gzip package size for use-lifecycle-ref in KB

Readme

useLifecycleRef
npm npm bundle size codecov Test
Like useRef, but with lifecycle and ref merging support

Quick Look

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>;
});

Support

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.

Issues and Feedback

Please voice your opinion and report bugs in the issues sections of this GitHub project.

Contributing

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.

License

MIT