UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

25 lines 1.23 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useControllableState = useControllableState; // https://github.com/chakra-ui/chakra-ui/tree/5ec0be610b5a69afba01a9c22365155c1b519136/packages/hooks/use-controllable-state const react_1 = require("react"); const useCallbackRef_1 = require("./useCallbackRef"); /** * `useControllableState` returns the state and function that updates the state, just like React.useState does. */ function useControllableState({ value: valueProp, defaultValue, onChange, }) { const onChangeProp = (0, useCallbackRef_1.useCallbackRef)(onChange); const [uncontrolledState, setUncontrolledState] = (0, react_1.useState)(defaultValue); const controlled = valueProp !== undefined; const value = controlled ? valueProp : uncontrolledState; const setValue = (0, useCallbackRef_1.useCallbackRef)((next) => { const setter = next; const nextValue = typeof next === "function" ? setter(value) : next; if (!controlled) { setUncontrolledState(nextValue); } onChangeProp(nextValue); }, [controlled, onChangeProp, value]); return [value, setValue]; } //# sourceMappingURL=useControllableState.js.map