Use controlled state
optics/use-controlled-stateFreeUtility
Hook utility: use-controlled-state
See it running
Open the demo on optics
optics.agusmayol.com.ar/components/use-controlled-stateInstall it
npx shadcn@latest add https://optics.agusmayol.com.ar/r/use-controlled-state.jsonSource
1import * as React from "react";23// eslint-disable-next-line @typescript-eslint/no-explicit-any4export function useControlledState(props) {5 const { value, defaultValue, onChange } = props;67 const [state, setInternalState] = React.useState(8 value !== undefined ? value : defaultValue,9 );1011 React.useEffect(() => {12 if (value !== undefined) setInternalState(value);13 }, [value]);1415 const setState = React.useCallback(16 (next, ...args) => {17 setInternalState(next);18 onChange?.(next, ...args);19 },20 [onChange],21 );2223 return [state, setState];24}
Files it writes
More from optics
All 79 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Cursor Rule: Back Endcursor-rule-back-end | optics | Utilities | Free | no deps | |
| Cursor Rule: Bulk Processingcursor-rule-bulk-processing | optics | Utilities | Free | no deps | |
| Cursor Rule: Commits Conventioncursor-rule-commits-convention | optics | Utilities | Free | no deps | |
| Cursor Rule: Front Endcursor-rule-front-end | optics | Utilities | Free | no deps | |
| Cursor Rule: Generalcursor-rule-general | optics | Utilities | Free | no deps | |
| Cursor Rule: React Optimizationcursor-rule-react-optimization | optics | Utilities | Free | no deps | |
| Cursor Rule: Web Interface Guidelinescursor-rule-web-interface-guidelines | optics | Utilities | Free | no deps | |
| Get strict contextget-strict-context | optics | Utilities | Free | no deps |
