Skip to content

useControlledState ​

useControlledState is a React hook that allows you to control both controlled and uncontrolled states. If you pass the state to value, it will be a controlled state, and if you pass the state to defaultValue, it will be an uncontrolled state. If both value and defaultValue are passed, value will take precedence.

Interface ​

ts
function useControlledState<T>(props: Object): [T, Dispatch<SetStateAction<T>>];

Parameters ​

  • propsrequired · Object

    • props.valueT

      The value of the state.

    • props.defaultValueT

      The default value of the state.

    • props.onChange(value: T) => void

      The callback function that is called when the state changes.

    • props.equalityFn(prev: T, next: T) => boolean

      The function that is used to compare the previous and next values.

Return Value ​

  • [T, Dispatch<SetStateAction<T>>]

    The state and the setter function.

Example ​

tsx
type ToggleProps = {
  value?: boolean;
  defaultValue?: boolean;
  onChange?: (value: boolean) => void;
};

function Toggle({ value, defaultValue, onChange }: ToggleProps) {
  const [on, setOn] = useControlledState({
    value,
    defaultValue: defaultValue ?? false,
    onChange,
  });

  return (
    <button onClick={() => setOn(prev => !prev)}>{on ? 'ON' : 'OFF'}</button>
  );
}

Released under the MIT License.