Skip to content

Instantly share code, notes, and snippets.

@paoloricciuti
Created January 21, 2022 08:39
Show Gist options
  • Select an option

  • Save paoloricciuti/ea8b9996e4b702924260da88a1efeb5c to your computer and use it in GitHub Desktop.

Select an option

Save paoloricciuti/ea8b9996e4b702924260da88a1efeb5c to your computer and use it in GitHub Desktop.
useCallbackState.js
import { useEffect, useRef, useState } from "react";
const useCallbackState = (initialValue) => {
const [state, _setState] = useState(initialValue);
const callbackQueue = useRef([]);
useEffect(() => {
callbackQueue.current.forEach((cb) => cb(state));
callbackQueue.current = [];
}, [state]);
const setState = (newValue, callback) => {
_setState(newValue);
if (callback && typeof callback === "function") {
callbackQueue.current.push(callback);
}
};
return [state, setState];
};
export default useCallbackState;
@fentonius
Copy link

very cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment