Dhananjay Patel Logo
  1. Home
  2. / Blog
  3. / Controlled Vs Uncontrolled
  4. / Lessons
  5. / 1

Prev

1. Controlled Component

Controlled Components are those in which form’s data is handled by the component’s state. It takes its current value through props and makes changes through callbacks like onClick, onChange, etc. A parent component manages its own state and passes the new values as props to the controlled component.

Astro theme cactus logo

App.js
import { useState } from "react"
const App = () => {
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
function onSubmit(e) {
e.preventDefault()
// YOUR SUBMIT CODE GOES HERE
console.log({email, password})
}
return (
<form onSubmit={onSubmit}>
<label htmlFor="email">Email</label>
<input
value={email}
onChange={e => setEmail(e.target.value)}
type="email"
id="email"
/>
<label htmlFor="password">Password</label>
<input
value={password}
onChange={e => setPassword(e.target.value)}
type="password"
id="password"
/>
<button type="submit">Submit</button>
</form>
)
}
export default App

Controlled components are great and very easy to work with, but there is a performance bottleneck as the element is rendered everytime the input filelds changes (i.e, email field and password field in above code).

It’s not the end of the world, we can limit the re-render by using memo hook and other existing method; and most of the time we don;t bother with the rerender as the changes are not noticible.

Sometime we do want this functionality like if we want to validate the email or password strength on realtime when user enters the keystroke.

Prev