'React Checkbox is not checked immediately unless all other components render
In my react application. I have a simple use case where I have a checkbox. When you mark the checkbox as checked, it shows other large number of components.
Now, the checkbox still remain unchecked till everything render and after everything renders then only it gets checked.
function App() {
return (
<>
<A />
</>
);
}
function A() {
const [checked, setChecked] = React.useState(false);
return (
<div>
<label>
<input type="checkbox"
defaultChecked={checked}
onChange={() => setChecked(!checked)}
/>
Check Me!
</label>
{checked ? "I am checked" : "I am unchecked"}
<B checked={checked} />
</div>
);
}
function B(props: any) {
const { checked } = props;
let nums = [];
const start = 0;
const end = 20000;
for (let i = start; i < end; i++) {
nums.push(i);
}
return (
<div>
{
checked && nums.map((num: number, index: number) => (
<C num={num} key={index} />
))
}
</div>
);
}
function C(props: any) {
const { num } = props;
return (
<div>
This is {num}
</div>
);
}
Below is the jsfiddle for the same.
https://jsfiddle.net/bwf594dv/1/
Any way we can make the check box change states as soon as it is clicked rathar than waiting for rest of the components to render?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
