Last active
July 1, 2020 21:49
-
-
Save mjackson/50d389b00728a55b8d526d258a8125e9 to your computer and use it in GitHub Desktop.
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
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