Skip to content

Instantly share code, notes, and snippets.

@mjackson
Last active July 1, 2020 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjackson/50d389b00728a55b8d526d258a8125e9 to your computer and use it in GitHub Desktop.
Save mjackson/50d389b00728a55b8d526d258a8125e9 to your computer and use it in GitHub Desktop.
function useControl(defaultValue, value, onChange) {
let [localValue, setLocalValue] = React.useState(defaultValue)
let isControlled = value != null // the key
let activeValue = isControlled ? value : localValue
let setActiveValue = nextValue => {
if (isControlled) {
if (onChange) {
onChange(nextValue)
} else {
// bad spot... we should warn them!
}
} else {
setLocalValue(nextValue)
if (onChange) {
onChange(nextValue)
}
}
}
return [activeValue, setActiveValue]
}
// Usage
function Widget({ defaultValue, value: valueProp, onChange }) {
let [value, setValue] = useControl(defaultValue, valueProp, onChange);
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment