Sometimes, we want to check know when a React ref.current value has changed.
In this article, we’ll look at how to check know when a React ref.current value has changed.
Check Know When a React ref.current Value Has Changed
To check know when a React ref.current value has changed, we can add a callback ref to watch for the ref’s value with a function.
For instance, we write:
import React, { useCallback, useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const onRefChange = useCallback(
(node) => {
console.log(node);
},
[count]
);
return (
<div>
<button onClick={() => setCount((c) => c + 1)}>increment</button>
<p ref={onRefChange}>{count}</p>
</div>
);
}
We call the useCallback
hook with a function that takes the node
parameter.
node
is the ref.current
value since we pass the returned callback as the value of the ref
prop.
We set count
as the value to watch in the 2nd argument of useCallback
.
Now when we update the count
by clicking the button, the useCallback
callback should be called.
And we see the node
‘s value logged in the console after each change of count
.
node
is the p
element with the latest value of count
since we’re watching count
‘s value as specified in the 2nd argument of useCallback
.
Conclusion
To check know when a React ref.current value has changed, we can add a callback ref to watch for the ref’s value with a function.