I try to default a date in a date input. Here is the code
import { useEffect } from "react";
const DateInput = ({ handleDateInput }) => {
const curr = new Date();
const date = curr.toISOString().substring(0, 10);
useEffect(() => {
handleDateInput(date);
});
return (
<>
<label htmlFor="inputDate" className="form-label">
Date measured
</label>
<div className="input-group">
<input
id="inputDate"
type="date"
className="form-control"
onInput={(e) => handleDateInput(e.target.value)}
defaultValue={date}
/>
</div>
</>
);
};
export default DateInput;
The handleDateInput is a useState()
setState
from its parent. I do it like that <DateInput handleDateInput={setDate} />
For some reason the handleDateInput seems not be triggered when I call handleDateInput()
anywhere before, either in the declaration or in the useEffect()
.
Can someone explain why this could be the case and how can I fix that?
My goal is to set a default state once the component is rendered. I know that I could set the default state in the useState
but I want the DateInput
component to take care of what is the default.
CodePudding user response:
useEffect without dependency array is run after each render, what happens here is that you call setState in child, parent re-render, child call setState again...causing an infinite loop. You can solve this by adding an empty dependency array
useEffect(() => {
const curr = new Date();
const date = curr.toISOString().substring(0, 10);
handleDateInput(date);
}, []);