React controlled and uncontrolled hooks
Manish Baral
Posted on June 17, 2024
In React, controlled and uncontrolled components are patterns used to manage form inputs. React Hooks introduced the concepts of controlled and uncontrolled hooks to manage state within functional components. Here’s an overview:
Controlled Hooks:
useState Hook: With controlled hooks, state is managed directly by React. The useState
hook allows you to declare state variables and update them using setter functions provided by React. When a component's state changes, React re-renders the component with the updated state.
import React, { useState } from 'react';
function ControlledComponent() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<input
type="text"
value={value}
onChange={handleChange}
/>
);
}
In this example, the input field’s value
is controlled by the value state variable, and updates are handled by the setValue
function.
Uncontrolled Hooks:
useRef Hook: Uncontrolled hooks allow you to manage state directly within the DOM rather than through React’s state management system. The useRef
hook creates a mutable ref object whose current
property can hold a value that persists across renders without causing a re-render.
import React, { useRef } from 'react';
function UncontrolledComponent() {
const inputRef = useRef(null);
const handleClick = () => {
console.log(inputRef.current.value);
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Log Value</button>
</div>
);
}
In this example, the input field’s value is managed directly by the DOM via the inputRef.current.value
, and updates are accessed without involving React's state management system.
Choosing Between Controlled and Uncontrolled Hooks:
- Controlled Hooks: Use controlled hooks when you need React to manage and synchronize the state of form inputs across your application. Controlled components provide a single source of truth for form data, making it easier to track and manage changes.
- Uncontrolled Hooks: Use uncontrolled hooks when you need direct access to DOM elements or when dealing with large forms where controlled components might lead to performance issues. Uncontrolled components can be faster because they don’t trigger re-renders for every state change. However, they may be harder to track and manage, especially in complex applications.
Both controlled and uncontrolled hooks have their use cases, and the choice depends on your specific requirements and preferences.
Posted on June 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
December 21, 2023