I want to update and re-render for loop test condition on hook state update. After I update state hook the state is rerendered but I want to the loop to be rerendered too. I make a form. The length of the form depends on what number I enter on input.
Here is what I tried:
JavaScript
x
14
14
1
const [formLength, setFormLength] = useState(0);
2
3
let eachForm = () => {
4
for (let x = 0; x < formLength; x++) {
5
return <div>{x+1} inpute</div>;
6
}
7
};
8
9
useEffect(() => {
10
eachForm();
11
}, [formLength]);
12
13
{formLength <= 0 ? (<>Zeroo</>) : (<><eachForm /></>)}
14
Advertisement
Answer
There is no need for the useEffect
hook here, it’s not doing anything for you. You can render directly the JSX from the formLength
state. eachForm
also isn’t a valid React component, so it can’t be used like <eachForm />
. The for-loop
will also return during the first iteration and not return an array of div
elements like I suspect you are expecting.
Example:
JavaScript
1
12
12
1
const [formLength, setFormLength] = useState(10);
2
3
return (
4
<>
5
{formLength
6
? Array.from({ length: formLength }).map((_, i) => (
7
<div key={i}>{i+1} input</div>
8
))
9
: <>Zero</>
10
</>
11
);
12