UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

22 lines 1.02 kB
// https://github.com/chakra-ui/chakra-ui/tree/5ec0be610b5a69afba01a9c22365155c1b519136/packages/hooks/use-controllable-state import { useState } from "react"; import { useEventCallback } from "./useEventCallback.js"; /** * `useControllableState` returns the state and function that updates the state, just like React.useState does. */ export function useControllableState({ value: valueProp, defaultValue, onChange, }) { const onChangeProp = useEventCallback(onChange); const [uncontrolledState, setUncontrolledState] = useState(defaultValue); const controlled = valueProp !== undefined; const value = controlled ? valueProp : uncontrolledState; const setValue = useEventCallback((next) => { const setter = next; const nextValue = typeof next === "function" ? setter(value) : next; if (!controlled) { setUncontrolledState(nextValue); } onChangeProp(nextValue); }); return [value, setValue]; } //# sourceMappingURL=useControllableState.js.map