-
Notifications
You must be signed in to change notification settings - Fork 83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Ensure useFromNow does not trigger any re-render (impl dom level update) #905
base: main
Are you sure you want to change the base?
Conversation
Quality Gate passedIssues Measures |
We don't have to merge it if you don't want to but it's intresting enough |
export function useFromNow(params: { dateTime: number | undefined }) { | ||
const { dateTime } = params; | ||
|
||
const id = useId(); | ||
|
||
const fromNowText = useMemo(() => <span id={id}></span>, [id]); | ||
|
||
const updateNode = useConstCallback(() => { | ||
if (dateTime === undefined) { | ||
return; | ||
} | ||
|
||
const el = document.getElementById(id); | ||
|
||
if (el === null) { | ||
return; | ||
} | ||
|
||
el.innerHTML = fromNow({ dateTime }); | ||
}); | ||
|
||
useEffect(() => { | ||
updateNode(); | ||
}, [dateTime, id]); | ||
|
||
useEffect(() => { | ||
const timer = setInterval(updateNode, 1000); | ||
|
||
return () => clearInterval(timer); | ||
}, []); | ||
|
||
return { fromNowText }; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is an interesting implementation. In my opinion, it's much more convenient that the hook returned a string instead of a ReactNode
. Additionally, there is a type issue: fromNowText
is currently typed as any
. While this implementation is more complex than the previous one and has some benefits, I don’t believe they are sufficient to justify merging it.
No description provided.