Skip to content

Instantly share code, notes, and snippets.

@eps1lon
Created February 21, 2019 12:51
Show Gist options
  • Save eps1lon/47109f9734892b1abf80711b396910c8 to your computer and use it in GitHub Desktop.
Save eps1lon/47109f9734892b1abf80711b396910c8 to your computer and use it in GitHub Desktop.
useControlled
function useIsControlled(value) {
const { current: isControlled } = React.useRef(value != null);
return isControlled;
}
function useControlled(config) {
const { value, defaultValue, setControlledValue } = config;
const isControlled = useIsControlled(value);
const [state, setState] = React.useState(defaultValue);
return isControlled ? [value, setControlledValue] : [state, setState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment