Skip to content

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

@jhogg11

Description

@jhogg11

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];
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions