I have the following simple react component
import { useFormik } from 'formik';
import React from 'react';
const MyForm = () => {
const initialValues = {
date: new Date().toISOString().slice(0, 10), // Get the current date in YYYY-MM-DD format
// other form fields...
};
const onSubmit = (values) => {
// Handle form submission
console.log(values);
};
const formik = useFormik({
initialValues,
onSubmit,
});
return (
<form onSubmit={formik.handleSubmit}>
<div>
<label htmlFor="date">Date:</label>
<input
type="date"
id="date"
name="date"
onChange={formik.handleChange}
value={formik.values.date}
/>
</div>
{/* other form fields... */}
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
My question is why when I'm writing date: new Date()
the component gots re-render infinitely, on the other hand when I write date: new Date().toISOString().slice(0, 10)
it works fine. what is the reason behind that?
In javascript, there are two types of variables - reference and primitive.
This expression new Date().toISOString().slice(0, 10)
returns string - primitive type so the component doesn't re-render infinitely because the comparison of the string values remains consistent.
But in the case of new Date()
, the component re-renders infinitely because it creates a new Date object every render. objects are compared by reference, the new Date object is considered different from the previous one, even if the date and time values are the same.
To avoid the infinite re-rendering issue, you need to use a consistent value for the initial state, such as the string format obtained by new Date().toISOString().slice(0, 10)
, as you have done in your code.