Urgent.News

What's breaking now, across thousands of outlets.

Tech

One Prop Per State: Rethinking React's Controlled/Uncontrolled Boilerplate

If you've ever wrapped a <Select> , <DatePicker> , or <Dialog> , you've written this: function Select ({ value , defaultValue , onChange }) { const [ internal , setInternal ] = useState ( defaultValue ); const isControlled = value !== undefined ; // runtime mode check const current = isControlled ? value : internal ; // two sources of truth useEffect (() => { if ( isControlled ) setInternal (…

Controlled and uncontrolled components in React often lead to boilerplate code and unnecessary complexity. The react-use-control hook offers a solution that simplifies state management by using a single source of truth without the need for synchronization effects or mode detection.

The core idea is to determine the state's origin by asking whether the parent already created it or not. If it exists, the component uses it; otherwise, it creates it locally. This approach eliminates the need for two separate sources of truth (controlled and uncontrolled) and reduces the amount of code required to manage state.

Rather than branching based on whether a component is controlled or uncontrolled, react-use-control offers a control object that allows the component to determine state ownership automatically. When a plain value is passed, the component operates in uncontrolled mode, using the provided value as the default. When a control is passed, the component operates in controlled mode, with the parent and child sharing the same source of truth.

This pattern simplifies the component's code by removing the need for branches and effects, improving performance and maintainability. The control object acts as a locator to the parent-created or newly-created state, enabling seamless sharing of state between components without the need for additional context or middleware.

While react-use-control provides a streamlined approach to state management, it's important to note that it is not intended to replace existing state management solutions. In certain cases, such as when fields are managed by form libraries like react-hook-form or formik, using the form's API is recommended. However, react-use-control excels in scenarios where components require independent state management without the overhead of additional context or middleware.

The library is lightweight, with only 80 lines of code and no dependencies, making it easy to integrate into projects. It works seamlessly with React's standard setState flow, SSR, StrictMode, and concurrent rendering features, ensuring compatibility with modern React applications.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Tuesday 1 September →