Hayk Safaryan
Hayk Safaryan

Reputation: 2056

Formatted date with date-ins doesn't update on re-renders in React component

Having a strange issue using date-fns with react. Didn't encounter anything like this before.

Basically there is a component which gets a year number as a prop, which is then used to create a date string using format from date-fns. But later when year prop changes the formatted strings stay the same. At first I thought it has something to do with useMemo. But even without useMemo these strings stay the same even tho the prop changes.

import { startOfYear, endOfYear, format } from "date-fns";
import { useMemo } from "react";
import { formatDateToYearMonthDay } from "./formatDateToYearMonthDay";

interface IProps {
  year?: number;
}

export function ForecastInfo({ year = new Date().getFullYear() }: IProps) {
  console.log("year", year);

  // const fromDateMemoDateFns = useMemo(
  //   () => formatDateToYearMonthDay(startOfYear(year)),
  //   [year]
  // );
  // const toDateMemoDateFns = useMemo(
  //   () => formatDateToYearMonthDay(endOfYear(year)),
  //   [year]
  // );

  // Why the hell stays the same?
  const fromDateMemoDateFns = format(startOfYear(year), "yyyy-MM-dd");

  const toDateMemoDateFns = format(endOfYear(year), "yyyy-MM-dd");

  const fromDateMemo = useMemo(() => `${year}-01-01`, [year]);
  const toDateMemo = useMemo(() => `${year}-12-31`, [year]);

  const fromDate = `${year}-01-01`;
  const toDate = `${year}-12-31`;

  const requestParams = {
    FromDate: fromDate,
    ToDate: toDate,
  };

  console.log("requestParams", requestParams);

  return (
    <div>
      <p>Year: {year}</p>
      <p>fromDate: {fromDate}</p>
      <p>toDate: {toDate}</p>
      <p>fromDateMemo: {fromDateMemo}</p>
      <p>toDateMemo: {toDateMemo}</p>
      <p>fromDateMemoDateFns: {fromDateMemoDateFns}</p>
      <p>toDateMemoDateFns: {toDateMemoDateFns}</p>
    </div>
  );
}

Also here is code sandbox: https://codesandbox.io/p/sandbox/2wmlq2?file=%2Fsrc%2FApp.tsx%3A23%2C17

Upvotes: 0

Views: 26

Answers (0)

Related Questions