Languages
[Edit]
EN

React - custom use current callback hook / useCurrentCallback

3 points
Created by:
Root-ssh
177780

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);

Alternative titles

  1. React - setInterval with custom useCurrentCallback hook
  2. React - optimal way how to use setInterval
  3. React - optimal way how to use intervals
  4. React - custom useCallback hook that updates current function
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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