Created
October 18, 2022 02:36
-
-
Save InfiniteXyy/72091888a21ff2570dc52fb7bb2120e1 to your computer and use it in GitHub Desktop.
decouple use, and state, memo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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