Skip to content

Commit

Permalink
Merge pull request #904 from InseeFrLab/fix-rerender-issue
Browse files Browse the repository at this point in the history
Do not cause rerender when fromNowText has not changed
  • Loading branch information
garronej authored Dec 19, 2024
2 parents 2a6ca87 + 1042278 commit ae775c0
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions web/src/ui/shared/formattedDate/useFormattedDate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo, useEffect, useReducer } from "react";
import { useMemo, useEffect, useState } from "react";
import { useLang } from "ui/i18n";
import { getFormattedDate } from "./getFormattedDate";
import { fromNow } from "./dateTimeFormatter";
Expand All @@ -15,23 +15,27 @@ export function useFormattedDate(params: { time: number }): string {
export function useFromNow(params: { dateTime: number }) {
const { dateTime } = params;

const [trigger, forceUpdate] = useReducer(n => n + 1, 0);
const { lang } = useLang();

const [fromNowText, setFromNowText] = useState(() => fromNow({ dateTime }));

useEffect(() => {
const timer = setInterval(() => forceUpdate(), 1000);
const updateText = () => {
const newText = fromNow({ dateTime });

return () => {
clearTimeout(timer);
if (fromNowText !== newText) {
setFromNowText(newText);
}
};
}, []);

const { lang } = useLang();
updateText();

const fromNowText = useMemo(
() => fromNow({ dateTime }),
const timer = setInterval(updateText, 1000);

[lang, trigger, dateTime]
);
return () => {
clearInterval(timer);
};
}, [dateTime, lang]);

return { fromNowText };
}

0 comments on commit ae775c0

Please sign in to comment.