Skip to content

Instantly share code, notes, and snippets.

@tokland
Created January 6, 2021 12:21
Show Gist options
  • Save tokland/8edce4cc6f3d0cd08d6c369ada6da2ea to your computer and use it in GitHub Desktop.
Save tokland/8edce4cc6f3d0cd08d6c369ada6da2ea to your computer and use it in GitHub Desktop.
React hook for optional value/setValue
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