Skip to content

Instantly share code, notes, and snippets.

@lxchurbakov
Created June 11, 2024 08:04
Show Gist options
  • Save lxchurbakov/402915fb1b4338621c76057935726ba1 to your computer and use it in GitHub Desktop.
Save lxchurbakov/402915fb1b4338621c76057935726ba1 to your computer and use it in GitHub Desktop.
useBetween
const getDispatcher = () => {
return (React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current;
};
const setDispatcher = (w: any) => {
(React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current = w;
};
const useForceUpdate = ([v, setv] = useState(false)) =>
React.useCallback(() => setv(($: any) => !$), [setv]);
const allboxes = new Map();
const useBetween = (predicate: any) => {
if (!allboxes.has(predicate)) {
allboxes.set(predicate, []);
}
const boxes = allboxes.get(predicate);
let index = 0;
const forceUpdate = useForceUpdate();
index = 0;
let oldDispatcher = getDispatcher();
const mockUseState = (def: any) => {
let currentIndex = index++;
if (!boxes[currentIndex]) {
boxes[currentIndex] = { value: def };
}
const box = boxes[currentIndex];
return [box.value, ($: any) => {
box.value = $;
forceUpdate();
console.log('updated', $)
}];
};
setDispatcher({ ...oldDispatcher, useState: mockUseState });
let result = predicate();
setDispatcher(oldDispatcher);
allboxes.set(predicate, boxes);
return result;
};
const useAuth = () => {
const [user, setUser] = React.useState(3);
return [user, setUser];
};
const _useAuth = () => useBetween(useAuth);
const Wtf = () => {
const [shit, upd] = _useAuth();
return (
<div>
{shit}
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment