Skip to content

Instantly share code, notes, and snippets.

@InfiniteXyy
Created October 18, 2022 02:36
Show Gist options
  • Save InfiniteXyy/72091888a21ff2570dc52fb7bb2120e1 to your computer and use it in GitHub Desktop.
Save InfiniteXyy/72091888a21ff2570dc52fb7bb2120e1 to your computer and use it in GitHub Desktop.
decouple use, and state, memo
function use<
T extends { type: 'state'; value: unknown } | { type: 'memo'; fn: unknown },
>(
parameters: T,
): T extends { type: 'state'; value: infer V }
? [V, React.SetStateAction<V>]
: T extends { type: 'memo'; fn: () => infer R }
? R
: never {
const { type } = parameters;
if (type === 'state') {
return useState(parameters.value);
}
if (type === 'memo') {
return useMemo(parameters.fn);
}
}
function state<T>(value: T) {
return { type: 'state', value } as const;
}
function memo<T>(fn: () => T) {
return { type: 'memo', fn } as const;
}
const [count, setCount] = use(state(1));
const memoCount = use(
memo(() => {
return 1;
}),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment