Skip to content

Instantly share code, notes, and snippets.

@RazerMoon
Created November 15, 2020 18:37
Show Gist options
  • Save RazerMoon/8b40282253b0d34d0af4df6f179a64ee to your computer and use it in GitHub Desktop.
Save RazerMoon/8b40282253b0d34d0af4df6f179a64ee to your computer and use it in GitHub Desktop.
Basic visualization of how React useState works (passing parameters to a callback function) (useful for custom hooks)
// https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABDAzgMXNeYAUpKwIAqcAwgBYCmEA1gFyLg1hwDuYAlIgN4BQiAxACdKUEEKT4sxMlVqIAZAp4BfAHRQ4AZShCYYAOZqIAQwA2ZvJkJgSFajS4BeF4gDkAbTgAjAFbUoRAwCbABdNwBuXhVeXjNRRAhxETAoHRMoSgYTMABPKN4pG0QAfRRRdMycMEpWADVzECzEHNyuPkFkYEQcVGDpXBr6xsoOdv5OwSShFLSoDMpEJ0QhhrMmnGnZytGJgRVESjNynj3JrcpUnaWV2rWms5iYwutsRnKdgB4tAD5esBgsHM92aWnGnQuV3mmRu+kBMGBI1inREYgkiA8kLmCwANKVytjMqEWihEggUFBorEIOTAh4KbjEASdsTliAPtDKHhzOUOLFmZycDgAA4iABuDG8cDg8Ryzh+iAAhKLKGK+bwaWAUDLKGozHADJtkpdCaNEAB6c2ITRwRBmEwAL1y1ttAFsTDRFgyYaw4EIaIhvCBArk4CBEAYElAqMgACaUExAA
function isFunction(functionToCheck: unknown) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
let currentState: any;
function _setState(newValue: any) {
if (isFunction(newValue)) {
currentState = newValue(currentState)
} else {
currentState = newValue
}
}
function useState<S>(initialValue: S) {
currentState = initialValue
return [currentState, _setState] as const
}
const [state, setState] = useState(false)
setState((prev: boolean) => !prev)
console.log(currentState) // too lazy to make state work but you get the idea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment