Like useEffect
, but optimized for ref
.
- Guaranteed to execute only when ref is either attached or detached.
- Minimize re-rendering as the returned ref is always stable.
- Perfect for setting and cleaning up event listeners compared to
useEffect
. - Written in TypeScript with absolutely minimal bundle size.
Here is a simple demonstration.
import { useRefEffect } from 'use-ref-effect';
export function Component(props) {
const ref = useRefEffect<HTMLDivElement>((el) => {
console.log(`${el} attached`);
function onClick() {
console.log('clicked');
}
el.addEventListener('click', onClick);
return () => {
el.removeEventListener('click', onClick);
console.log(`${el} detached`);
};
});
return <div ref={ref}>Hello World</div>;
}
- This hook is more akin to the currently experimental
useEffectEvent
hook than typicaluseEffect
hook. The effect callback is NOT reactive (i.e. always capture the latest values without the need to signal an update through a dependency array). In other words, the effect and its cleanup only re-run when the returnedref
is updated by DOM mutation or the equivalent actions when used for other purposes. - Different from
useEffect
,useRefEffect
NEVER runs on the initial render. This is because React executesRefCallback
the first time after the underlying resource is available. In the case ofreact-dom
, it is after the DOM element is first rendered into the actual DOM tree.
This library is used in most of my personal projects, and is regarded as production-ready by myself. In the foreseeable future, I will continuously maintain and support this library.
Please voice your opinions 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