EN
React - custom use current callback hook / useCurrentCallback
3
points
In this short article we would like to show how to create custom useCurrentCallback hook in React.
Below code uses useRef hook to store callback reference. When component is re-rendered callback reference is updated letting us to have access to most recent callback. That approach may be useful when we want to share callback between many nested components.
Motivation to use current callback approach is reduced numer of
useEffectcalls - putconsole.log('call')line at begining of theruseEffectarrow function to see result.
Practical example:
// ONLINE-RUNNER:browser;
//import React from 'react';
//import ReactDOM from 'react-dom';
const useCurrentCallback = (callback) => {
const reference = React.useRef();
reference.current = callback;
return (...args) => {
return reference.current?.(...args);
};
};
const App = () => {
const [counter, setCounter] = React.useState(0);
const currentCallback = useCurrentCallback(() => {
setCounter(counter + 1);
});
React.useEffect(() => {
const handle = setInterval(currentCallback, 100);
return () => clearInterval(handle);
}, []);
return (
<div>counter: {counter}</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);