Created
January 6, 2021 12:21
-
-
Save tokland/8edce4cc6f3d0cd08d6c369ada6da2ea to your computer and use it in GitHub Desktop.
React hook for optional value/setValue
This file contains 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
import React from "react"; | |
export interface OptControlledValue<T> { | |
value?: T; | |
set?: (value: T) => void; | |
initial: T; | |
} | |
export function useMaybeControlledValue<T>(options: OptControlledValue<T>): [T, (val: T) => void] { | |
const optionsSet = options.set; | |
const [stateValue, setStateValue] = React.useState(options.initial); | |
const setValueAndNotifyParent = React.useCallback( | |
(newValue: T) => { | |
setStateValue(newValue); | |
if (optionsSet) optionsSet(newValue); | |
}, | |
[optionsSet] | |
); | |
if (options.value === undefined && options.set === undefined) { | |
return [stateValue, setStateValue]; | |
} else if (options.value === undefined && options.set !== undefined) { | |
return [stateValue, setValueAndNotifyParent]; | |
} else if (options.value !== undefined && options.set === undefined) { | |
return [options.value, noop]; | |
} else if (options.value !== undefined && options.set !== undefined) { | |
return [options.value, options.set]; | |
} else { | |
throw new Error(); | |
} | |
} | |
const noop = () => {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment