Controlled Versus Uncontrolled Components in React

Kunal Singh

Nov 5, 2022

Handling Forms can be challenging in react as we usually have to maintain the state of each form element using the useState hook. For simple use-cases this may be simple enough, but when we try to work with other forms of inputs like checkbox,radio things start getting complex. This can be avoided using an alternate method.But before that let us understand what do we mean by Controlled and Uncontrolled Components.

What are Controlled Components?

To put it simply, It is a component whose state is managed and updated via the useState hook in react.

// Controlled Component 

import * as React from 'react';

export default function ControlledForm() {
let [name, setname] = React.useState('');
let [age, setage] = React.useState('');
let [gender, setgender] = React.useState('');

const handleSubmit = (e) => {
e.preventDefault();
let payload = { name, age, gender };
console.log(payload);
// sendDatatoAPI(payload)
};

const handleChange = (e) => {
switch (e.target.name) {
case 'name':
setname(e.target.value);
break;
case 'age':
setage(e.target.value);
break;
case 'gender':
setgender(e.target.value);
break;
}
};

return (
<form onSubmit={handleSubmit}>
<legend>Controlled Form</legend>
<input
type="text"
placeholder="name"
name="name"
value={name}
onChange={handleChange}
/>

<input
type="number"
placeholder="age"
name="age"
value={age}
onChange={handleChange}
/>

<input
type="text"
placeholder="gender"
name="gender"
value={gender}
onChange={handleChange}
/>

<button>Submit</button>
</form>
);
}

As we can see here, we are taking care of the form state, changes via the useState hook.Now lets understand what are Uncontrolled Components.

What are Uncontrolled Components?

Uncontrolled Components stores their own state internally using native Browser API support just like a HTML page would do, and you query the DOM for the `form` element using a ref to find its current value when you need it. This is a bit more like traditional HTML.

// Uncontrolled Component 


import * as React from 'react';

export default function UncontrolledForm() {
const formRef = React.useRef();
const handleSubmit = (e) => {
e.preventDefault();
let form = formRef.current;
let formData = new FormData(form);
let values = [...formData.entries()];
let valuesToJSON = Object.fromEntries(values);
console.log(values);
console.log(valuesToJSON);
// sendDatatoAPI(valuesToJSON)
};

return (
<form onSubmit={handleSubmit} ref={formRef}>
<legend>Uncontrolled Form</legend>
<input type="text" placeholder="name" name="name" />
<input type="number" placeholder="age" name="age" />
<input type="text" placeholder="gender" name="gender" />
<button>Submit</button>
</form>
);
}

To understand this example a little better, I have created a codesandbox example which you can check out

Live Example

I hope you learned something new today if you did then please share this post with your friends who might find this useful aswell. Have any questions? Feel free to connect with me on LinkedIn Twitter @singhkunal2050. You can also write me here.

Happy Coding 👩‍💻!

Recommendations

Are You Still Using Basic CSS? Here Are 7 Tricks to Get Ahead of the Curve

#css

Bored of the same old CSS? Unleash 7 hidden gems to take your designs to the...

Dec 27, 2023

Easiest way to store your logs in a file WITHOUT chaging the source file(node)

#productivity

Often, developers face challenges when dealing with a flood of logs in the...

Dec 21, 2023

Build Your Own Pinterest-Style Masonry Grid: A Step-by-Step Guide

#css

,

#web

,

#layout

Create a masonary grid layout with left to right content flow, supporting...

Dec 10, 2023

Using git diff and git apply to Share Local Changes with Peers

#git

,

#productivity

,

#software_engeneering

,

#dev

git diff and git apply are two powerful Git commands that can be used to share...

Nov 12, 2023

React Portals: Render Components Outside the current DOM Hierarchy

#react

,

#web

The createPortal API in React allows you to render child elements into a...

Jul 27, 2023

Cloning Made Easy: Try degit and Clone Directories within Repos.

#git

,

#productivit

Have you ever faced the dilemma of wanting just a small portion of a repository,...

Jul 19, 2023

Debugging Web Apps with Browser Dev Tools: 6 Amazing Tricks

#browser

,

#debugging

,

#web

Debugging web applications can be a challenging task, with errors like...

Jul 13, 2023

Format Numbers, Dates and Currencies with the Intl Object in Javascript

#javascript

,

#html

,

#web

Intl object can be used to format data into commonly used formats of dates,...

Sep 13, 2022

Image Masking on Hover Using CSS Clip Path and Javascript

#javscript

,

#css

,

#html

Image Masking can be used to add fancy hover highlight effects to images for...

Jul 23, 2022

Recreating CSS Tricks Fancy Grid Hover Effect

#html

,

#css

,

#UI

,

#recreation

CSS Trick had a simple yet cool grid layout which I found dope. So lets try to...

May 21, 2022

File Explorer Recursive React Component

#react

,

#javascript

,

#web

How to create a recursive folder Component using react.

Apr 16, 2022

Add Google Fonts to Your React & NextJS + TailwindCSS Project (Next 14)

#css

,

#tailwindcss

,

#react

,

#nextjs

,

#tailwind

,

#design

Use Google Fonts in Your TailwindCSS Projects

Apr 6, 2022

Event Delegation in Javascript

#javscript

,

#css

,

#html

,

#web

,

#performance

Handling multiple Events in Javascript with minimal CPU Usage

Mar 6, 2022

A Simple Web Accessibility Trick that you most probably missed!

#html

,

#css

,

#web-accessibility

,

#user-experience

Imagine that you cannot use the mouse and have to Navigate a Website with the...

Dec 23, 2021

Top Terminal Commands I Use For Productivity

#linux

,

#cli

,

#terminal

The whole point of development is solving problems. But very often we Developers...

Nov 3, 2021

CSS Logical Properties

#css

,

#html

CSS logical properties are properties which are used to design element on the...

Oct 5, 2021

Fluid Typography in CSS 💧

#css

,

#html

,

#typography

CSS Best Practices in Fluid Typography

Aug 15, 2021

CSS Units in a Nutshell 🐚

#css

,

#html

Are you still writing your css units in pixels and percentages? if you are then...

Aug 8, 2021

Master Markdown in 5minutes ⌚

#markdown

,

#documentation

Markdown is a lightweight markup language for creating formatted text using a...

Aug 1, 2021

What is JAMStack ✨

#jamstack

Jamstack stands for Javascript APIS and Markup and it is based on this idea of...

Jul 31, 2021

+

Check my latest Blog Post

Are You Still Using Basic CSS? Here Are 7 Tricks to Get Ahead of the Curve

Read Now
Oh My Gawwdd!!!!!!!

Wow you have been viewing my site since 20 seconds!

+
+