20 Feb 2024
Intermediate
In React.js, controlled and uncontrolled components refer to two different approaches for handling form inputs and managing their state.
-
Controlled Components:
- Controlled components are those where form data is controlled by React components.
- In controlled components, the form data is handled by React components through state.
- The input elements receive their current value through props and notify changes via callbacks like
onChange
. - Whenever the user interacts with the form, React state is updated to reflect the changes, and the UI is re-rendered accordingly.
- Controlled components provide more control over form data and enable validation and synchronization across multiple inputs easily.
- Example:
import React, { useState } from 'react'; function ControlledComponentExample() { const [value, setValue] = useState(''); const handleChange = (event) => { setValue(event.target.value); }; return ( <input type="text" value={value} onChange={handleChange} /> ); } export default ControlledComponentExample;
-
Uncontrolled Components:
- Uncontrolled components are those where form data is handled by the DOM itself.
- In uncontrolled components, the form data is managed by the DOM, typically using refs.
- React doesn't control the state of the input elements directly; instead, it relies on the DOM to manage and update the input state.
- Uncontrolled components are often useful when integrating with non-React code or when you want to keep the React component lightweight.
- Example:
import React, { useRef } from 'react'; function UncontrolledComponentExample() { const inputRef = useRef(null); const handleClick = () => { console.log('Input Value:', inputRef.current.value); }; return ( <div> <input type="text" ref={inputRef} /> <button onClick={handleClick}>Get Value</button> </div> ); } export default UncontrolledComponentExample;
In summary, controlled components are managed by React state, while uncontrolled components delegate state management to the DOM itself using refs. The choice between controlled and uncontrolled components depends on your specific requirements and the complexity of your application.