Languages
[Edit]
EN

React - custom use current callback hook / useCurrentCallback

3 points
Created by:
Root-ssh
91240

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 useEffect calls - put console.log('call') line at begining of ther useEffect arrow 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);

ReactJS

React - custom use current callback hook
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join