use-state-with-callback icon indicating copy to clipboard operation
use-state-with-callback copied to clipboard

State ref to address stale state issue with lazy function

Open jhogg11 opened this issue 4 years ago • 0 comments

Love the module, but I was running into stale state issues.

This might be a useful addition:

const useStateRefWithCallbackLazy = initialValue => {
	const valueRef = useRef(initialValue);
	const callbackRef = useRef(null);

	const [value, setValue] = useState(initialValue);

	useEffect(() => {
		if (callbackRef.current) {
			callbackRef.current();

			callbackRef.current = null;
		}
	}, [value]);

	const setValueWithCallback = (newValue, callback) => {
		valueRef.current = newValue;
		callbackRef.current = callback;

		return setValue(newValue);
	};

	return [value, valueRef, setValueWithCallback];
};

jhogg11 avatar Jun 09 '21 02:06 jhogg11