I have just made a input box with onChange event handler and I have a checkbox. I clicked on checkbox to true and then I type in input box which will re-render the component as It has useState hook…But when the re- rendering happens why dont react just displays the checkbox with false value but rather it shows the previous state(that is true)???
import React, { useState } from "react";
function App() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<input
type="text"
onChange={handleChange}
placeholder="Enter a value"
value={name}
/>
<label>RADIO2</label>
<input type="checkbox" />
{console.log(name)}
</div>
);
}
export default App;
I just want to learn about this react behaviour of re-rendering.
2
Answers
You need to manage the state of the checkbox:
React uses a virtual DOM instead of the actual DOM. When a component’s state changes, React creates a new Virtual DOM and compares it with the older one. If React finds changes, it just updates the actual DOM. You can read more about the Virtual DOM here.
As per your code, when you type, the UI re-renders, and since the checkbox is not controlled by React, it retains the previous state. If you want the checkbox to behave as you intend, you have to let React control its state. Here’s how you can do that:
Step 1:
Use useState to store the state of the checkbox:
Step 2:
Create a function to handle the checkbox
Step 3:
Make these changes to the input to let React handle the state:
Your whole code should look like this: