---
> 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 hook change
- `mergeRefs` - merge multiple refs together. For, actually, fork
- `transformRef` - transform one ref to anther
- `refToCallback` - convert RefObject to an old callback-style ref
- `assignRef` - assign value to the ref, regardless of it's form
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 = (newValue) => {...}
const refObject = useCallbackRef(null, onRefUpdate);
// ...