---
> 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](https://reactjs.org/docs/hooks-reference.html#useref)
Read more about `use-callback` pattern and use cases:
- https://dev.to/thekashey/the-same-useref-but-it-will-callback-8bo
This library exposes helpers to handle any case related to `ref` _lifecycle_
- `useCallbackRef` - react on a ref change (replacement for `useRef`)
- `createCallbackRef` - - low level version of `useCallbackRef`
- `useMergeRefs` - merge multiple refs together creating a stable return ref
- `mergeRefs` - low level version of `useMergeRefs`
- `useTransformRef` - transform one ref to another (replacement for `useImperativeHandle`)
- `transformRef` - low level version of `useTransformRef`
- `useRefToCallback` - convert RefObject to an old callback-style ref
- `refToCallback` - low level version of `useRefToCallback`
- `assignRef` - assign value to the ref, regardless it is RefCallback or RefObject
All functions are tree shakable, but even together it's **less then 300b**.
# API
💡 Some commands are hooks based, and returns the same refs/functions every render.
But some are not, to be used in classes or non-react code.
## useRef API
🤔 Use case: every time you have to react to ref change
API is 99% compatible with React `createRef` and `useRef`, and just adds another argument - `callback`,
which would be called on **ref update**.
#### createCallbackRef - to replace React.createRef
- `createCallbackRef(callback)` - would call provided `callback` when ref is changed.
#### useCallbackRef - to replace React.useRef
- `useCallbackRef(initialValue, callback)` - 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.
```js
import { useRef, createRef, useState } from 'react';
import { useCallbackRef, createCallbackRef } from 'use-callback-ref';
const Component = () => {
const [, forceUpdate] = useState();
// I dont need callback when ref changes
const ref = useRef(null);
// but sometimes - it could be what you need
const anotherRef = useCallbackRef(null, () => forceUpdate());
useEffect(() => {
// now it's just possible
}, [anotherRef.current]); // react to dom node change
};
```
💡 You can use `useCallbackRef` to convert RefObject into RefCallback, creating bridges between the old and the new code
```js
// some old component
const onRefUpdate = (newRef) => {...}
const refObject = useCallbackRef(null, onRefUpdate);
// ...