Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

State ref to address stale state issue with lazy function #21

Open
jhogg11 opened this issue Jun 9, 2021 · 0 comments
Open

State ref to address stale state issue with lazy function #21

jhogg11 opened this issue Jun 9, 2021 · 0 comments

Comments

@jhogg11
Copy link

jhogg11 commented Jun 9, 2021

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];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant