---
> Keep in mind that useRef doesn't notify you when its content changes.
Mutating the .current property doesn't cause a re-render.
If you want to run some code when React attaches or detaches a ref to a DOM node,
you may want to use ~~a callback ref instead~~ .... __useCallbackRef__ instead.
– Hooks API Reference
API
useRef API
API is 99% compatible with React createRef
and useRef
, and just adds another argument - callback
,
which would be called on ref update.
-
createCallbackRef(callback)
- (aka React.createRef) would call provided callback when ref is changed.
-
useRef(initialValue, callback)
- (aka React.useRef)would call provided callback when ref is changed.
-
callback
in both cases is callback(newValue, oldValue)
. Callback would not be called if newValue and oldValue is the same.
import {useRef, createRef, useState} from 'react';
import {useCallbackRef, createCallbackRef} from 'use-callback-ref';
const Component = () => {
const [,forceUpdate] = useState();
const ref = useRef(null);
const anotherRef = useCallbackRef(null, () => forceUpdate());
useEffect( () => {
}, [anotherRef.current])
}
💡 You can use useCallbackRef
to convert RefObject into RefCallback, creating bridges between the old and the new code
const onRefUpdate = (newValue) => {...}
const refObject = useCallbackRef(null, onRefUpdate);
<SomeNewComponent ref={refObject}/>
Additional API
mergeRefs
mergeRefs(refs: arrayOfRefs, [defaultValue]):ReactMutableRef
- merges a few refs together
import React from 'react'
import {mergeRefs} from 'use-callback-ref'
const MergedComponent = React.forwardRef(function Example(props, ref) {
const localRef = React.useRef()
return <div ref={mergeRefs([localRef, ref])} />
})
based on https://github.com/smooth-code/react-merge-refs, just exposes RefObject, instead of callback
When developing low level UI components, it is common to have to use a local ref but also support an external one using React.forwardRef. Natively, React does not offer a way to set two refs inside the ref property. This is the goal of this small utility.
License
MIT